<template>
  <div>
    <el-card>
      <div class="filter">
        借款状态：
        <el-select v-model="genDataBody.status" placeholder="请选择类型">
          <el-option
            v-for="item in statusOptions"
            :key="item.label"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <!-- 渠道 -->
        渠道：
        <el-select
          v-model="genDataBody.channel"
          @clear="handleClear"
          clearable
          placeholder="请选择渠道"
        >
          <el-option
            v-for="item in channelList"
            :key="item.channelId"
            :label="item.name"
            :value="item.channelId"
          ></el-option>
        </el-select>
        <!-- 资方 -->
        资方：
        <el-select
          v-model="genDataBody.fundId"
          @clear="handleClear"
          clearable
          placeholder="请选择资方"
        >
          <el-option
            v-for="item in fundList"
            :key="item.fundId"
            :label="item.name"
            :value="item.fundId"
          ></el-option>
        </el-select>
      </div>
      <div class="filter">
        手机号：
        <el-input
          v-model="genDataBody.phoneNo"
          clearable
          placeholder="手机号"
          maxlength="11"
          style="width: 200px;"
        ></el-input>期数：
        <el-input v-model="genDataBody.term" clearable placeholder="期数" style="width: 200px"></el-input>金额：
        <el-input v-model="genDataBody.amount" clearable placeholder="金额" style="width: 200px"></el-input>
        <!-- 查询数据按钮 -->
        <el-button type="primary" @click="genData">生成数据</el-button>
      </div>
      <el-collapse v-model="activeCollapse">
        <el-collapse-item title="基本信息(非必填)" name="1">
          <div class="filter">
            姓名：
            <el-input v-model="genDataBody.name" clearable placeholder="姓名" style="width: 150px"></el-input>身份证号：
            <el-input
              v-model="genDataBody.idCardNo"
              clearable
              placeholder="身份证"
              style="width: 200px"
            ></el-input>
          </div>
          <div class="filter">
            银行卡号：
            <el-input
              v-model="genDataBody.bankCardNo"
              clearable
              placeholder="银行卡号"
              style="width: 200px"
            ></el-input>银行名称：
            <el-input
              v-model="genDataBody.bankName"
              clearable
              placeholder="银行名称"
              style="width: 200px"
            ></el-input>银行code：
            <el-input
              v-model="genDataBody.bankCode"
              clearable
              placeholder="银行code"
              style="width: 100px"
            ></el-input>
            <el-button type="primary" @click="reGenBankCardData">换一换</el-button>
          </div>
          <div class="filter" v-if="genDataBody.channel === 159886">
            利率：
            <el-input v-model="genDataBody.rate" placeholder="利率" style="width: 100px"></el-input>
            出账日：
            <el-input v-model="genDataBody.fixedBillDay" placeholder="出账日" style="width: 100px"></el-input>
            还款日：
            <el-input v-model="genDataBody.fixedRepayDay" placeholder="还款日" style="width: 100px"></el-input>
          </div>
        </el-collapse-item>
      </el-collapse>
      <!-- 数据表格 -->
      <div class="dataTable">
        <el-table :data="dataTableList" border style="width: 100%">
          <el-table-column prop="phoneNo" label="phone_no" width="150px"></el-table-column>
          <el-table-column prop="userId" label="user_id" width="100px"></el-table-column>
          <!-- <el-table-column prop="uuid" label="uuid" width="330px"></el-table-column> -->
          <el-table-column prop="registeredFrom" label="注册渠道id" width="120px"></el-table-column>
          <el-table-column prop="fundId" label="资方id" width="120px"></el-table-column>
          <el-table-column prop="createdAt" label="创建时间" width="200px"></el-table-column>
          <el-table-column prop="desc" label="状态" width="200px"></el-table-column>
          <!-- <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="primary" @click="retryToGen(scope.row.phoneNo)">重试</el-button>
            </template>
          </el-table-column>-->
        </el-table>
      </div>
      <!-- 日志区域 -->
      <div style="padding:20px 0px">
        <p v-if="genLog">实时日志:</p>
        <textarea
          id="textarea"
          v-if="genLog"
          v-model="genLog"
          style="min-height:600px;background-color:black;width:-webkit-fill-available;color:white"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import { uuid } from '@/utils/randomData'
import {
  genData,
  queryUserStatus,
  getSupportChannelAndFund
} from '@/api/genXyqbData'
import { getAll } from '@/api/testdata'
export default {
  data() {
    return {
      activeCollapse: ['1'],
      namespaceOptions: [],
      statusOptions: [
        { label: '审核通过', value: 0 },
        { label: '审核拒绝', value: 1 },
        { label: '放款中', value: 2 },
        { label: '放款成功', value: 3 },
        { label: '放款失败', value: 4 }
      ],
      fundList: [],
      channelList: [],
      selectNamespace: '',
      expectNum: '1',
      dataTableList: [],
      // 生成数据接口的body
      genDataBody: {
        namespace: window.sessionStorage.getItem('env'),
        status: '',
        phoneNo: '',
        name: '',
        idCardNo: '',
        channel: '',
        fundId: '',
        term: 6,
        amount: 10000,
        bankCardNo: '',
        bankName: '',
        bankCode: '',
        fixedBillDay: '2',
        fixedRepayDay: '12',
        rate: '31.86',
        symbol: ''
      },
      // 轮询状态
      loopStatus: '',
      timer: '',
      websock: null,
      genLog: ''
    }
  },
  methods: {
    // 随机生成用户基本信息
    getUserBasicInfo() {
      getAll({ count: 1 })
        .then((resp) => {
          let data = resp.data.data[0]
          this.genDataBody.name = data['name']
          this.genDataBody.idCardNo = data['IDCardNo']
          this.genDataBody.bankCardNo = data['bankNo']
          this.genDataBody.phoneNo = data['mobile']
          this.genDataBody.bankName = data['bankType'].split(' ')[0]
          this.genDataBody.bankCode = data['bankType'].split(' ')[1]
        })
        .catch((error) => console.log(error))
    },
    reGenBankCardData() {
      this.getUserBasicInfo()
    },
    // 获取资方和渠道列表
    getSupportChannelAndFund() {
      getSupportChannelAndFund().then((resp) => {
        this.channelList = resp.data.data.channelList
        this.fundList = resp.data.data.fundList
      })
    },
    // 造数据
    genData() {
      if (this.genDataBody.status === '') {
        return this.$message.error('借款状态不能为空！')
      }
      if (this.genDataBody.channel === '') {
        return this.$message.error('渠道不能为空！')
      }
      if (this.genDataBody.fundId === '') {
        return this.$message.error('资方不能为空！')
      }
      if (this.genDataBody.phoneNo === '') {
        return this.$message.error('手机号不能为空！')
      }
      this.genDataBody.symbol = uuid()
      // 请求造数据接口
      genData(this.genDataBody)
        .then((resp) => {
          if (resp.data.data === false) {
            // 结束轮询
            this.loopStatus = this.genDataBody.status
            this.queryGenProgress(this.genDataBody.phoneNo)
            return this.$message.error('数据生成失败！')
          } else {
            // 结束轮询
            this.loopStatus = this.genDataBody.status
            this.queryGenProgress(this.genDataBody.phoneNo)
            return this.$message.success('数据生成成功！')
          }
        })
        .catch((error) => {
          console.log(error)
          return this.$message.error('数据接口返回失败！')
        })
      this.$message.success('开始造数据！')
      this.initWebSocket()
      this.timer = setInterval(
        this.queryGenProgress,
        10000,
        this.genDataBody.phoneNo
      )
    },
    // 清空下拉框
    handleClear() {
      this.getSupportChannelAndFund()
    },
    // 查询造数据过程中的用户状态
    queryGenProgress(phoneNo) {
      queryUserStatus({
        namespace: window.sessionStorage.getItem('env'),
        phoneNo: phoneNo
      })
        .then((resp) => {
          this.loopStatus = resp.data.data.status
          var flag = 0
          // 如果数据已在表格中，则只更新状态
          this.dataTableList.forEach((item) => {
            if (item.phoneNo === resp.data.data.phoneNo) {
              item.desc = resp.data.data.desc
              item.fundId = resp.data.data.fundId
              flag = 1
            }
          })
          // 如果数据不在表格中，则将整条数据插入
          if (flag !== 1) {
            this.dataTableList.push(resp.data.data)
          }
        })
        .catch((error) => {
          console.log(error)
          // 查询状态报错后，清除状态轮询定时器
          clearInterval(this.timer)
        })
    },
    // todo
    retryToGen(phoneNo) {},
    initWebSocket() {
      const wsuri =
        'wss:' +
        process.env.QA_PLATFORM +
        '/websocket/' +
        this.genDataBody.symbol
      this.websock = new WebSocket(wsuri)
      this.websock.onopen = this.websocketonopen
      this.websock.onerror = this.websocketonerror
      this.websock.onmessage = this.websocketonmessage
      this.websock.onclose = this.websocketclose
    },
    websocketonopen() {
      console.log('WebSocket连接成功')
    },
    websocketonerror(e) {
      console.log('WebSocket连接发生错误')
    },
    // 接收消息
    websocketonmessage(e) {
      this.genLog += e.data
      this.genLog += '\n'
      var textarea = document.getElementById('textarea')
      if (textarea.scrollHeight) {
        textarea.scrollTop = textarea.scrollHeight
      }
    },
    websocketsend(agentData) {
      // 数据发送
      this.websock.send(agentData)
    },
    websocketclose(e) {
      // 关闭
      console.log('connection closed (' + e.code + ')')
    }
  },
  mounted() {
    this.getSupportChannelAndFund()
    this.getUserBasicInfo()
  },
  // 计算属性
  computed: {
    statusData() {
      return this.loopStatus
    }
  },
  watch: {
    statusData: function (newVal) {
      // if (newVal !== this.genDataBody.status) {
      //   var timer = setInterval(
      //     this.queryGenProgress,
      //     30000,
      //     this.genDataBody.phoneNo
      //   )
      // }
      // 当查询到的状态为最终状态时，结束轮询
      if (newVal === this.genDataBody.status) {
        clearInterval(this.timer)
      }
      // 当页面关闭的时候，结束轮询
      this.$once('hook:beforeDestory', () => {
        clearInterval(this.timer)
      })
    }
    // scrollToBottom: function () {
    //   this.$nextTick(() => {
    //     var textarea = document.getElementById('textarea')
    //     textarea.scrollTop = textarea.scrollHeight
    //   })
    // }
  }
}
</script>

<style lang="less" scoped>
.dataTable {
  margin-top: 20px;
}

.filter {
  margin-bottom: 15px;
  font-size: 14px;
}

.el-select {
  margin-right: 15px;
}

.el-input {
  margin-right: 15px;
}

.el-collapse {
  margin-top: 10px;
}
</style>
