<template>
  <div>
    <!-- 头部导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>数据工厂</el-breadcrumb-item>
      <el-breadcrumb-item>生成新数据</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <div>
        借款状态：
        <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" 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" placeholder="请选择资方">
          <el-option
            v-for="item in fundList"
            :key="item.fundId"
            :label="item.name"
            :value="item.fundId"
          ></el-option>
        </el-select>
      </div>
      <div>
        手机号：
        <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-input-number
          v-model="expectNum"
          @change="handleExpectNumChange"
          :min="1"
          :max="100"
          label="数据个数"
        ></el-input-number>-->
        <!-- 查询数据按钮 -->
        <el-button type="primary" style="margin-top:20px" @click="genData">生成数据</el-button>
      </div>
      <!-- 数据表格 -->
      <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
          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 '../../assets/api/utils'
export default {
  data() {
    return {
      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'),
        phoneNo: '',
        channel: '',
        term: '6',
        amount: '10000',
        fundId: '',
        status: '',
        symbol: ''
      },
      // 轮询状态
      loopStatus: '',
      timer: '',
      websock: null,
      genLog: ''
    }
  },
  methods: {
    // 获取资方和渠道列表
    getSupportChannelAndFund() {
      this.$axios.get('/gen/supportChannelAndFund').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.phone === '') {
        return this.$message.error('手机号不能为空！')
      }
      this.genDataBody.symbol = uuid()
      // 请求造数据接口
      this.$axios
        .post('/gen/loanUser', 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,
        30000,
        this.genDataBody.phoneNo
      )
    },
    // 查询造数据过程中的用户状态
    queryGenProgress(phoneNo) {
      this.$axios
        .get('/gen/userStatus', {
          params: {
            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)
          }
        })
    },
    // todo
    retryToGen(phoneNo) {},
    initWebSocket() {
      const wsuri = 'wss://qa-platform-pre.liangkebang.net/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'
    },
    websocketsend(agentData) {
      // 数据发送
      this.websock.send(agentData)
    },
    websocketclose(e) {
      // 关闭
      console.log('connection closed (' + e.code + ')')
    }
  },
  mounted() {
    this.getSupportChannelAndFund()
  },
  // 计算属性
  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)
      })
    }
  }
}
</script>

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

// .filter {
//   margin-bottom: 10px;
// }

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

.el-input {
  margin-right: 15px;
}
</style>
