<template>
  <section class="content">
    <div class="box box-primary">
      <div class="box-body">
        <!-- Content Header (Page header) -->
        <section class="content-header">
          <h1 id="itemTitle"></h1>
        </section>
        <!-- .content -->
        <section class="content">
          <div class="row">
            <form class="form-horizontal col-sm-6"
                  id="infoForm">
              <div class="form-group">
                <label for="ernos"
                       class="col-sm-2 control-label">平台ID（多个ID用换行分隔）:</label>
                <div class="col-sm-10">
                  <textarea class="form-control"
                            name="ernos"
                            id="ernos"
                            style="height:150px;"></textarea>
                </div>
              </div>
              <div class="form-group">
                <label for="type"
                       class="col-sm-2 control-label">备注:</label>
                <div class="col-sm-10">
                  <input type="text"
                         name="remark"
                         id="remark"
                         class="form-control"
                         maxlength="100"
                         placeholder="非必填">
                </div>
              </div>
              <div class="form-group">
                <label for="busType"
                       class="col-sm-2 control-label">分类:</label>
                <div class="col-sm-10">
                  <select id="busType"
                          name="busType"
                          class="form-control validate[required]">
                    <option value="">请选择...</option>
                  </select>
                </div>
              </div>
            </form>
            <form class="form-horizontal col-sm-6"
                  id="goldForm">
              <div class="form-group">
                <label for="num"
                       class="col-sm-2 control-label">数量:</label>
                <div class="col-sm-10">
                  <input type="text"
                         class="form-control validate[required]"
                         name="num"
                         id="num"
                         value="1">
                </div>
              </div>
              <div class="form-group">
                <label for="numTransfer"
                       class="col-sm-2 control-label">参考数量（美元）:</label>
                <div class="col-sm-10">
                  <input type="text"
                         class="form-control"
                         readonly
                         name="numTransfer"
                         id="numTransfer"
                         value="">
                </div>
              </div>
              <div class="form-group">
                <label for="type"
                       class="col-sm-2 control-label">活动类型:</label>
                <div class="col-sm-10">
                  <select name="type"
                          id="type"
                          class="form-control"
                          ata-btn-class="btn-warning"
                          onchange="selectOnchang(this)">
                    <option>请选择...</option>
                    <!-- <option value="OFFICAL_DIAMOND">官方赠送金币</option>
                    <option value="OFFICAL_RADISH">官方赠送水晶</option>
                    <option value="ACTIVITY_GOLD">活动奖励钻石</option>
                    <option value="COMPANY_ACCOUNT_DIAMOND">公款充值金币</option>
                    <option value="OFFICAL_REDUCE_DIAMONDS">官方金币消除</option>
                    <option value="OFFICAL_GOLD">官方赠送钻石</option>
                    <option value="CLEAR_USER_GOLD">用户钻石清除</option> -->
                    <!-- <option value="OFFICAL_RADISH">官方赠送萝卜</option>
                                       <option value="ACTIVITY_RADISH">活动奖励萝卜</option> -->
                  </select>
                </div>
              </div>
              <div class="form-group hidden"
                   id="actualAmountDiv">
                <label for="type"
                       class="col-sm-2 control-label">实际充值金额:</label>
                <div class="col-sm-10">
                  <input type="text"
                         name="actualAmount"
                         id="actualAmount"
                         class="form-control"
                         placeholder="必填">
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label"></label>
                <div class="col-sm-10">
                  <button type="button"
                          class="btn btn-primary"
                          id="btnScan">查看用户</button>
                  <button type="button"
                          class="btn btn-primary"
                          id="btnGive">确认</button>
                  <button type="button"
                          class="btn btn-primary"
                          id="btnGoldRecord">查看记录</button>
                  <!-- <button type="button" class="btn btn-primary" id="btnRadishRecord">查看萝卜记录</button> -->
                </div>
              </div>
            </form>
          </div><!-- ./row -->
        </section>
      </div>
    </div>
    <div class="box box-primary">
      <div class="box-body">
        <table class="table table-bordered"
               id="table">
          <!--<thead><tr>
                    <th style="width: 50px">头像</th>
                    <th style="width:200px;">耳伴号</th>
                    <th style="width:300px;">昵称</th>
                    <th>金币</th>
                </tr></thead>
                <tbody id="tbody">
                </tbody>-->
        </table>
      </div>
    </div>
    <!--查看金币赠送记录-->
  </section>
  <!-- .content -->
</template>

<script>
export default {
  name: "OfficicalGoldView",
  setup () {
    function selectOnchang (obj) {
      var type = $('#type').val();
      if (type == 'COMPANY_ACCOUNT_DIAMOND') {
        $('#actualAmountDiv').removeClass("hidden");
      } else {
        $('#actualAmountDiv').addClass("hidden");
      }
      $.get('/admin/goldcoin/busType/listByQuery', { status: 1, activityTypeEnum: $('#type').val() }, function (res) {
        if (res && res.code == 200) {
          var data = res.data;
          $('#busType').empty();
          $('#busType').append('<option value="">请选择...</option>');
          for (var i = 0; i < data.length; i++) {
            var item = data[i];
            $('#busType').append('<option value="' + item.id + '">' + item.busName + '</option>');
          }
        }
      });
    }
    window.selectOnchang = selectOnchang;
    return {
      selectOnchang
    };
  },
  created () {
    this.$nextTick(function () {
      this.initData();
    });
  },
  methods: {
    initData () {
      $(function () {
        $.get('/admin/goldcoin/listType', function (res) {
          if (res && res.code == 200) {
            var data = res.data;
            if (data.length > 0) {
              $('#type').empty();
              $('#type').append('<option value="">请选择...</option>');
              for (var i = 0; i < data.length; i++) {
                var item = data[i];
                $('#type').append('<option value="' + item.type + '">' + item.desc + '</option>');
              }
            }
          }
        });

        var isGiveBol = false;
        $("#goldForm").validationEngine();

        $.get('/admin/goldcoin/busType/listByQuery', { status: 1, activityTypeEnum: $('#type').val() }, function (res) {
          if (res && res.code == 200) {
            var data = res.data;
            if (data.length > 0) {
              $('#busType').empty();
              $('#busType').append('<option value="">请选择...</option>');
              for (var i = 0; i < data.length; i++) {
                var item = data[i];
                $('#busType').append('<option value="' + item.id + '">' + item.busName + '</option>');
              }
            }
          }
        });

        $('#num').on('input', function() {
          var numValue = $(this).val();
          if (numValue && !isNaN(numValue)) {
            var transferValue = (parseInt(numValue) / 30000).toFixed(2);
            $('#numTransfer').val(transferValue);
          } else {
            $('#numTransfer').val('');
          }
        });

        $('#btnScan').click(function () {
          if (!$('#ernos').val()) {
            $("#tipMsg").text("请输入耳伴号");
            $("#tipModal").modal('show');
            return;
          }
          $('#table').bootstrapTable('destroy');
          initUserInfoTable();
        });

        $("#btnGoldRecord").click(function () {
          if (!$('#ernos').val()) {
            $("#tipMsg").text("请输入兔兔号");
            $("#tipModal").modal('show');
            return;
          }
          $("#table").bootstrapTable('destroy');
          initGoldRecordTable();
        })

        $("#btnRadishRecord").click(function () {
          if (!$('#ernos').val()) {
            $("#tipMsg").text("请输入兔兔号");
            $("#tipModal").modal('show');
            return;
          }
          $("#table").bootstrapTable('destroy');
          initRadishRecordTable();
        })

        $("#btnGive").click(function () {
          //校验
          if (isGiveBol) {
            return;
          }
          var type = $('#type').val();
          var erBanNos = trimTextArea($("#ernos").val());
          var actualAmount = $('#actualAmount').val();
          var num = $('#num').val();
          var busType = $('#busType').val();
          var actualGold = parseInt(num);
          if (!erBanNos) {
            $("#tipMsg").text("请输入平台ID");
            $("#tipModal").modal('show');
            return;
          }
          if (type == 'COMPANY_ACCOUNT_DIAMOND') {
            if (!actualAmount) {
              $("#tipMsg").text("请输入实际充值金额数");
              $("#tipModal").modal('show');
              return;
            }
            let reg = actualAmount.match(/^[0-9]+(.[0-9]{1,3})?$/);
            if (reg == null) {
              $("#tipMsg").text("请输入合理的充值金额数");
              $("#tipModal").modal('show');
              return;
            }
            if (actualGold != parseInt(actualAmount * 30000)) {
              $("#tipMsg").text("赠送金币与充值金额兑换比例不正确！");
              $("#tipModal").modal('show');
              return;
            }
          }
          if (type != 'CLEAR_USER_GOLD' && type != 'OFFICAL_GOLD') {
            if (busType == null || busType.trim() == '') {
              $("#tipMsg").text("请填写分类");
              $("#tipModal").modal('show');
              return;
            }
          }
          if (isGiveBol) {
            return;
          }
          //参数
          var reg = actualAmount.match(/^[0-9]+(.[0-9]{1,3})?$/);
          var remark = $('#remark').val();
          var data = {
            'ernos': erBanNos,
            'type': type,
            'num': num,
            'actualAmount': actualAmount,
            'remark': remark,
            'busType': busType
          };
          if (type == 'CLEAR_USER_GOLD') {
            clearUserGold(data);
          } else {
            give(data);
          }
        });

        function give (data) {
          isGiveBol = true;
          if (confirm('确认吗？')) {
            $("#tipMsg").text("处理中，请稍后...");
            $("#tipModal").modal('show');
            $.ajax({
              type: "post",
              url: "/admin/goldcoin/give",
              data: data,
              dataType: "json",
              success: function (json) {
                if (json.code == 200) {
                  $("#tipMsg").text("处理成功");
                  $('#btnScan').click();
                } else {
                  $("#tipMsg").text("处理出错，errorCode: " + json.message);
                }
                isGiveBol = false;
              },
              error: function (json) {
                $("#tipMsg").text("处理出错，网络出错");
                isGiveBol = false;
              }
            });
          }
        }

        function check () {
          if (isGiveBol) {
            return;
          }
          var type = $('#type').val();
          var erBanNos = trimTextArea(("#ernos").val());
          var actualAmount = $('#actualAmount').val();
          var num = $('#num').val();
          var busType = $('#busType').val();
          if (!erBanNos) {
            $("#tipMsg").text("请输入平台ID");
            $("#tipModal").modal('show');
            return;
          }
          if (type == 'COMPANY_ACCOUNT_DIAMOND') {
            if (!actualAmount) {
              $("#tipMsg").text("请输入实际充值金额数");
              $("#tipModal").modal('show');
              return;
            }
            var reg = actualAmount.match(/^[0-9]+(.[0-9]{1,3})?$/);
            if (reg == null) {
              $("#tipMsg").text("请输入合理的充值金额数");
              $("#tipModal").modal('show');
              return;
            }
            const actualGold = parseInt(num);
            if (actualGold != parseInt(actualAmount * 30000)) {
              $("#tipMsg").text("赠送金币与充值金额兑换比例不正确！");
              $("#tipModal").modal('show');
              return;
            }
          }
          if (type != 'CLEAR_USER_GOLD') {
            if (busType == null || busType.trim() == '') {
              $("#tipMsg").text("请填写分类");
              $("#tipModal").modal('show');
              return;
            }
          }
        }

        function clearUserGold (data) {
          isGiveBol = true;
          if (confirm('确认吗？')) {
            $("#tipMsg").text("处理中，请稍后...");
            $("#tipModal").modal('show');
            $.ajax({
              type: "post",
              url: "/admin/goldcoin/clearUserGold",
              data: { erBanNos: data.ernos, num: data.num },
              dataType: "json",
              success: function (json) {
                if (json.code == 200) {
                  $("#tipMsg").text("处理成功");
                  $('#btnScan').click();
                } else {
                  $("#tipMsg").text("处理出错，errorCode: " + json.message);
                }
                isGiveBol = false;
              },
              error: function (json) {
                $("#tipMsg").text("处理出错，网络出错");
                isGiveBol = false;
              }
            });
          }
        }

        function trimTextArea (str) {
          return str.split('\n').map((line) => line.trim())
            .filter(str => str && '' != str).join('\n');
        }
      });
    }
  },

};

function initUserInfoTable () {
  $('#table').bootstrapTable({
    columns: [
      {
        field: 'avatar',
        title: '头像',
        align: 'center',
        width: '5%',
        valign: 'middle',
        formatter: function (val, row, index) {
          if (val != null && (val.indexOf("http") == 0 || val.indexOf("https") == 0)) {
            return "<img src='" + val + "' height='106'>";
          } else {
            return "-";
          }
        }
      },
      { field: 'erbanNo', title: '耳伴号', align: 'center', width: '5%', valign: 'middle' },
      { field: 'nick', title: '昵称', align: 'center', width: '5%', valign: 'middle' },
      { field: 'goldNum', title: '钻石', align: 'center', width: '5%', valign: 'middle' },
      { field: 'radishNum', title: '水晶', align: 'center', width: '5%', valign: 'middle' },
      { field: 'diamondsNum', title: '金币', align: 'center', width: '5%', valign: 'middle' },
      { field: 'gameUsdNum', title: '游戏薪资', align: 'center', width: '5%', valign: 'middle' },
      { field: 'guildUsdNum', title: '薪资', align: 'center', width: '5%', valign: 'middle' }
    ],
    cache: false,
    striped: true,
    showRefresh: false,
    pageSize: 20,
    pagination: true,
    pageList: [20, 50, 100, 200, 300, 500],
    search: false,
    sidePagination: "server", //表示服务端请求
    //设置为undefined可以获取pageNumber，pageSize，searchText，sortName，sortOrder
    //设置为limit可以获取limit, offset, search, sort, order
    queryParamsType: "undefined",
    queryParams: function queryParams (params) {   //设置查询参数
      var param = {
        page: params.pageNumber,
        pageSize: params.pageSize,
        "ernos": $("#ernos").val(),
      };
      return param;
    },
    toolbar: '#toolbar',
    url: '/admin/goldcoin/userinfo',
    onLoadSuccess: function () {  //加载成功时执行
      console.log("load success");
    },
    onLoadError: function () {  //加载失败时执行
      console.log("load fail");
    }
  })
}

//初始化查看记录表格
function initGoldRecordTable () {
  $('#table').bootstrapTable({
    columns: [
      {
        field: 'avatar',
        title: '头像',
        align: 'center',
        width: '5%',
        valign: 'middle',
        formatter: function (val, row, index) {
          if (val != null && val.indexOf("https") == 0) {
            return "<img src='" + val + "' height='106'>";
          } else {
            return "-";
          }
        }
      },
      { field: 'erbanNo', title: '兔兔号', align: 'center', width: '5%', valign: 'middle' },
      { field: 'nick', title: '昵称', align: 'center', width: '5%', valign: 'middle' },
      { field: 'money', title: '余额', align: 'center', width: '5%', valign: 'middle' },
      { 
        field: 'goldNum', 
        title: '赠送数量', 
        align: 'center', 
        width: '5%', 
        valign: 'middle',
        formatter: function (val, row, index) {
          // 根据条件判断显示哪个字段
          // 示例：根据typeCn字段的值来决定显示什么
          if (row.currencyType == 0 || row.currencyType == 4 || row.currencyType == 5) {

            if(row.currencyType == 0 && row.diamondNum  == null){
            return row.goldNum 
            }else{
            return row.diamondNum 
            }
          }else if(row.currencyType == 1 || row.currencyType == 2){
            return row.goldNum 
          }
        }
      },
      { field: 'typeCn', title: '赠送类型', align: 'center', width: '5%', valign: 'middle' },
      { field: 'busName', title: '赠送分类', align: 'center', width: '5%', valign: 'middle' },
      { field: 'remark', title: '备注', align: 'center', width: '10%', valign: 'middle' },
      {
        field: 'createTime',
        title: '操作日期',
        align: 'center',
        width: '5%',
        valign: 'middle',
        formatter: function (val, row, index) {
          if (val) {
            var date = new Date(val);
            return date.format("yyyy-MM-dd hh:mm:ss");
          } else {
            return '-';
          }
        }
      },
      { field: 'operatorName', title: '操作人', align: 'center', width: '5%', valign: 'middle' }
    ],
    cache: false,
    striped: true,
    showRefresh: false,
    pageSize: 20,
    pagination: true,
    pageList: [20, 50, 100, 200, 300, 500],
    search: false,
    sidePagination: "server", //表示服务端请求
    //设置为undefined可以获取pageNumber，pageSize，searchText，sortName，sortOrder
    //设置为limit可以获取limit, offset, search, sort, order
    queryParamsType: "undefined",
    queryParams: function queryParams (params) {   //设置查询参数
      var type = $('#type').val();
      console.log('type: ' + type);
      var param = {
        page: params.pageNumber,
        pageSize: params.pageSize,
        ernos: $("#ernos").val(),
      };
      return param;
    },
    toolbar: '#toolbar',
    url: '/admin/goldcoin/record',
    onLoadSuccess: function () {  //加载成功时执行
      console.log("load success");
    },
    onLoadError: function () {  //加载失败时执行
      console.log("load fail");
    }
  })
}

//初始化查看记录表格
function initRadishRecordTable () {
  $('#table').bootstrapTable({
    columns: [
      {
        field: 'avatar',
        title: '头像',
        align: 'center',
        width: '5%',
        valign: 'middle',
        formatter: function (val, row, index) {
          if (val != null && val.indexOf("https") == 0) {
            return "<img src='" + val + "' height='106'>";
          } else {
            return "-";
          }
        }
      },
      { field: 'erbanNo', title: '平台号', align: 'center', width: '5%', valign: 'middle' },
      { field: 'nick', title: '昵称', align: 'center', width: '5%', valign: 'middle' },
      { field: 'radish', title: '萝卜余额', align: 'center', width: '5%', valign: 'middle' },
      { field: 'goldNum', title: '赠送萝卜数量', align: 'center', width: '5%', valign: 'middle' },
      { field: 'typeCn', title: '赠送类型', align: 'center', width: '5%', valign: 'middle' },
      { field: 'remark', title: '备注', align: 'center', width: '10%', valign: 'middle' },
      {
        field: 'createTime',
        title: '操作日期',
        align: 'center',
        width: '5%',
        valign: 'middle',
        formatter: function (val, row, index) {
          if (val) {
            var date = new Date(val);
            return date.format("yyyy-MM-dd hh:mm:ss");
          } else {
            return '-';
          }
        }
      },
      { field: 'operatorName', title: '操作人', align: 'center', width: '5%', valign: 'middle' }
    ],
    cache: false,
    striped: true,
    showRefresh: false,
    pageSize: 20,
    pagination: true,
    pageList: [20, 50, 100, 200, 300, 500],
    search: false,
    sidePagination: "server", //表示服务端请求
    //设置为undefined可以获取pageNumber，pageSize，searchText，sortName，sortOrder
    //设置为limit可以获取limit, offset, search, sort, order
    queryParamsType: "undefined",
    queryParams: function queryParams (params) {   //设置查询参数
      var param = {
        currencyType: 1,
        page: params.pageNumber,
        pageSize: params.pageSize,
        "ernos": $("#ernos").val(),
      };
      return param;
    },
    toolbar: '#toolbar',
    url: '/admin/goldcoin/record',
    onLoadSuccess: function () {  //加载成功时执行
      console.log("load success");
    },
    onLoadError: function () {  //加载失败时执行
      console.log("load fail");
    }
  })
}
</script>

<style scoped></style>