<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>
        <div id="toolbar">
          <div class="col-sm-12">
            <button id="btnSearch"
                    class="btn btn-default">
              <i class="glyphicon glyphicon-search"></i>查询
            </button>
            <button id="btnAdd"
                    class="btn btn-default">
              <i class="glyphicon glyphicon-plus"></i>增加
            </button>
          </div>
        </div>
      </div>
      <!-- .content -->
      <div id="table"></div>
    </div>
  </section>

  <div class="modal fade"
       id="roomTagModal"
       tabindex="-1"
       role="dialog"
       aria-labelledby="modalLabel">
    <div class="modal-dialog"
         role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button"
                  class="close"
                  data-dismiss="modal"
                  aria-label="Close"><span aria-hidden="true">&times;</span>
          </button>
          <h4 class="modal-title"
              id="modalLabel">资源位</h4>
        </div>
        <div class="modal-body">
          <form class="form-horizontal"
                id="addForm">
            <input type="hidden"
                   name="id"
                   id="id" />
            <div class="form-group">
              <label for="partitionId"
                     class="col-sm-3 control-label">选择地区：</label>
              <div class="col-sm-9">
                <select name="partitionId"
                        id="partitionId"
                        class="col-sm-3 form-control">
                </select>
              </div>
            </div>
            <!--A策略-->
            <div class="form-group">
              <label for="resourceA"
                     class="col-sm-3 control-label">A策略<font color="red">*</font>：</label>
              <div class="col-sm-9">
                <select name="status"
                        id="resourceA"
                        class="form-control validate[required]">
                  <option value=""></option>
                  <option value="1">牌照房</option>
                  <option value="2">相亲房</option>
                  <option value="3">PK房</option>
                  <option value="4">游戏房</option>
                  <option value="5">H5</option>
                  <option value="6">自定义房间</option>
                  <option value="7">个播房</option>
                </select>
              </div>
            </div>
            <div class="form-group">
              <label class="col-sm-3 control-label">A图标<font color="red">*</font>：</label>
              <div class="col-sm-8">
                <img src=""
                     id="iconImgUrlA"
                     style='width:108px;height:45px;'
                     alt="">
                <input type="file"
                       id="iconFileA"
                       name='uploadFile'
                       accept='image/gif,image/jpeg,image/jpg,image/png,image/svg'>
                <button class="btn btn-success"
                        type='button'
                        id="iconBtnA">上传</button>
                <input type="hidden"
                       id="iconUrlA"
                       name='alertWinPic'
                       class="form-control validate[required]">
              </div>
            </div>
            <div class="form-group"
                 id="boxA">
              <label for="contentA"
                     class="col-sm-3 control-label"
                     id="contentLabA"></label>
              <div class="col-sm-9">
                <input type="text"
                       class="form-control validate[required]"
                       name="name"
                       id="contentA">
              </div>
            </div>

            <!--B策略-->
            <div class="form-group">
              <label for="resourceB"
                     class="col-sm-3 control-label">B策略<font color="red">*</font>：</label>
              <div class="col-sm-9">
                <select name="status"
                        id="resourceB"
                        class="form-control validate[required]">
                  <option value=""></option>
                  <option value="1">牌照房</option>
                  <option value="2">相亲房</option>
                  <option value="3">PK房</option>
                  <option value="4">游戏房</option>
                  <option value="5">H5</option>
                  <option value="6">自定义房间</option>
                  <option value="7">个播房</option>
                </select>
              </div>
            </div>
            <div class="form-group">
              <label class="col-sm-3 control-label">B图标<font color="red">*</font>：</label>
              <div class="col-sm-8">
                <img src=""
                     id="iconImgUrlB"
                     style='width:108px;height:45px;'
                     alt="">
                <input type="file"
                       id="iconFileB"
                       name='uploadFile'
                       accept='image/gif,image/jpeg,image/jpg,image/png,image/svg'>
                <button class="btn btn-success"
                        type='button'
                        id="iconBtnB">上传</button>
                <input type="hidden"
                       id="iconUrlB"
                       name='alertWinPic'
                       class="form-control validate[required]">
              </div>
            </div>
            <div class="form-group"
                 id="boxB">
              <label for="contentB"
                     class="col-sm-3 control-label"
                     id="contentLabB"></label>
              <div class="col-sm-9">
                <input type="text"
                       class="form-control validate[required]"
                       name="name"
                       id="contentB">
              </div>
            </div>
            <div class="form-group">
              <label class="col-sm-3 control-label">生效时段<font color="red">*</font>:</label>
              <div class="col-sm-8">
                <input type="text"
                       class="input-sm datetime validate[required]"
                       name="beginTime"
                       id="beginTime">
                -<input type="text"
                       class="input-sm datetime validate[required]"
                       name="endTime"
                       id="endTime">
              </div>
            </div>

          </form>
        </div>
        <div class="modal-footer">
          <button type="button"
                  class="btn btn-default"
                  data-dismiss="modal">关闭</button>
          <button type="button"
                  class="btn btn-primary"
                  id="add">确定</button>
        </div>

      </div>
    </div>
  </div>
</template>

<script>
import TableHelper from '@/utils/bootstrap-table-helper';
import { serverError, formatTime } from '@/utils/maintainer';

export default {
  name: "RecommendResourceAdminView",
  setup () {
    return {};
  },
  created () {
    this.$nextTick(function () {
      this.initData();
    });
  },
  methods: {
    initData () {
      $(function () {
        $.ajax({
          type: 'get',
          url: '/partition/listPartitionInfo',
          dataType: 'json',
          success: function (json) {
            if (json.code == 200) {
              var partitionId = $("#partitionId");
              partitionId.empty();

              // 遍历数据并添加 option
              $.each(json.data, function (index, item) {
                // 创建新的 option 元素
                var option = $('<option></option>')
                  .attr('value', item.id)  // 设置 value 属性
                  .text(item.desc);           // 设置文本内容

                // 追加到 select 元素
                partitionId.append(option.clone());
              });
            }
          }
        });

        $('.datetime').datetimepicker({
          format: 'yyyy-mm-dd hh:ii:00',
          autoclose: true
        });

        $("#beginTime").datetimepicker({
          minView: "month",
          language: 'zh-CN',
          todayBtn: 1,
          autoclose: 1
        }).on("changeDate", function (event) {
          $("#endTime").datetimepicker('setStartDate', event.date);
        });

        $("#endTime").datetimepicker({
          minView: "month",
          language: 'zh-CN',
          todayBtn: 1,
          autoclose: 1,
          useCurrent: false
        }).on("changeDate", function (event) {
          $("#beginTime").datetimepicker('setEndDate', event.date);
        });

        $('#table').bootstrapTable('destroy');
        $('#table').bootstrapTable({
          columns: [
            { field: 'id', title: '序号', align: 'center', width: '5%' },
            {
              field: 'partitionId',
              title: '地区',
              align: 'center',
              width: '10%',
              formatter: function (val, row, index) {
                let value = '';
                if ((val & 1) != 0) {
                  value += '英语区<br>';
                }
                if ((val & 2) != 0) {
                  value += '阿拉伯语区<br>';
                }
                if ((val & 4) != 0) {
                  value += '华语区<br>';
                }
                if ((val & 8) != 0) {
                  value += '土耳其区<br>';
                }
                if ((val & 16) != 0) {
                  value += '英语2区<br>';
                }
                if ((val & 32) != 0) {
                  value += '独联体<br>';
                }
                return value;
              }
            },
            {
              field: 'resourceA',
              title: 'A',
              align: 'center',
              width: '15%',
              formatter: function (val) {
                return pardeResourceType(val);
              }
            },
            {
              field: 'resourceB',
              title: 'B',
              align: 'center',
              width: '15%',
              formatter: function (val) {
                return pardeResourceType(val);
              }
            },
            {
              field: 'beginTime', title: '开始时间', align: 'center', valign: 'middle', width: '10%',
              formatter: function (val, row, index) {
                if (val) {
                  var date = new Date(val);
                  return date.format('yyyy-MM-dd hh:mm:ss');
                } else {
                  return '-';
                }
              }
            },
            {
              field: 'endTime', title: '结束时间', align: 'center', valign: 'middle', width: '10%',
              formatter: function (val, row, index) {
                if (val) {
                  var date = new Date(val);
                  return date.format('yyyy-MM-dd hh:mm:ss');
                } else {
                  return '-';
                }
              }
            },
            {
              field: 'id',
              title: '操作',
              align: 'center',
              width: '10%',
              formatter: function (val, row, index) {
                if (row.isDefault) return '';
                return '<button id="btnEdit" name="btnEdit" class="btn btn-sm btn-success opt-edit" data-id="' + val + '" data-index="' + index + '">' +
                  '<i class="glyphicon glyphicon-edit"></i> 编辑</button>' +
                  '&nbsp;&nbsp;<button class="btn btn-sm btn-danger opt-remove" data-id="' + val +
                  '" data-index="' + index + '"><i class="glyphicon glyphicon-remove"></i>删除</button>';
              }
            }
          ],
          undefinedText: "-",
          cache: false,
          striped: true,
          showRefresh: false,
          pageSize: 10,
          pagination: true,
          pageList: [20, 50, 100, 200, 300, 500],
          search: false,
          sidePagination: "server", //表示服务端请求
          queryParamsType: "undefined",
          queryParams: function queryParams (params) {   //设置查询参数
            var param = {
              pageNum: params.pageNumber,
              pageSize: params.pageSize
            };
            return param;
          },
          ajax: function (request) {                    //使用ajax请求
            $.ajax({
              type: "GET",
              url: '/admin/home/resource/list',
              contentType: 'application/json;charset=utf-8',
              dataType: 'json',
              data: request.data,
              success: function (res) {
                apiResult(res);
                request.success({
                  rows: res.data.rows,
                  total: res.data.total,
                });
              },
              error: function (req) {
                serverError(req);
              }
            })
          },
          toolbar: '#toolbar',
          onLoadSuccess: function () {  //加载成功时执行
            console.log("load success");
          },
          onLoadError: function () {  //加载失败时执行
            console.log("load fail");
          }
        });


        // 查询刷新
        $('#btnSearch').on('click', function () {
          TableHelper.doRefresh('#table');
        });

        //新建标签
        $("#btnAdd").click(function () {
          clearModal();
          $("#boxA").hide();
          $("#boxB").hide();
          $("#roomTagModal").modal('show');
        });

        $("#add").click(function () {
          var strategySeq = $("#id").val();
          var resourceA = $("#resourceA").val();
          var resourceB = $("#resourceB").val();

          var iconA = $("#iconUrlA").val();
          var iconB = $("#iconUrlB").val();

          var contentA = $("#contentA").val();
          var contentB = $("#contentB").val();

          var beginTime = $("#beginTime").val();
          var endTime = $("#endTime").val();
          var partitionId = $('#partitionId').val();

          if (iconA == null || iconA == '') {
            $("#tipMsg").text("保存失败，请先上传图片！");
            $("#tipModal").modal('show');
            return;
          }

          if (iconB == null || iconB == '') {
            $("#tipMsg").text("保存失败，请先上传图片！");
            $("#tipModal").modal('show');
            return;
          }

          if ($("#addForm").validationEngine('validate')) {
            $.ajax({
              type: "post",
              url: "/admin/home/resource/saveResource",
              data: {
                strategySeq: strategySeq,
                resourceA: resourceA,
                resourceB: resourceB,
                iconA: iconA,
                iconB: iconB,
                contentA: contentA,
                contentB: contentB,
                beginTime: beginTime,
                endTime: endTime,
                partitionId: partitionId,
              },
              dataType: "json",
              success: function (json) {
                if (json.code == 200) {
                  $("#tipMsg").text("保存成功");
                  $("#tipModal").modal('show');
                  TableHelper.doRefresh("#table");
                  $("#roomTagModal").modal('hide');
                } else {
                  $("#tipMsg").text("保存失败." + json.message);
                  $("#tipModal").modal('show');
                  TableHelper.doRefresh("#table");
                  $("#roomTagModal").modal('hide');
                }
              }
            });
          }

        });

        $("#table").on("click", '.opt-edit', function () {
          const currentData = $('#table').bootstrapTable('getData')[$(this).data('index')];
          let partitionId = currentData.partitionId;
          var seq = $(this).attr("data-id");
          clearModal();

          $.ajax({
            type: "get",
            url: "/admin/home/resource/getResourceByStrategySeq",
            data: {
              seq: seq,
              partitionId: partitionId,
            },
            dataType: "json",
            success: function (res) {
              var json = res.data;
              if (json) {
                $("#id").val(seq);
                $("#resourceA").val(json.resourceA);
                $("#resourceB").val(json.resourceB);

                if (json.resourceA == 5 || json.resourceA == 6) {
                  $("#contentA").val(json.contentA);
                  $("#boxA").show();
                } else {
                  $("#contentA").val('');
                  $("#boxA").hide();
                }
                if (json.resourceB == 5 || json.resourceB == 6) {
                  $("#contentB").val(json.contentB);
                  $("#boxB").show();
                } else {
                  $("#contentB").val('');
                  $("#boxB").hide();
                }

                $("#beginTime").val(formatTime(json.beginTime));
                $("#endTime").val(formatTime(json.endTime));


                $('#iconUrlA').val(json.iconA);
                $('#iconImgUrlA').attr('src', json.iconA);

                $('#iconUrlB').val(json.iconB);
                $('#iconImgUrlB').attr('src', json.iconB);

                $('#partitionId').val(json.partitionId);

                // 打开编辑弹窗
                $("#roomTagModal").modal('show');
                $("#modalLabel").text("编辑房间标签");
              } else {
                $("#tipMsg").text("获取信息出错");
                $("#tipModal").modal('show');
              }
            }
          });
        });

        $("#table").on("click", '.opt-remove', function () {
          const currentData = $('#table').bootstrapTable('getData')[$(this).data('index')];
          let partitionId = currentData.partitionId;
          var seq = $(this).attr("data-id");
          if (seq == 'undefined') {
            $("#tipMsg").text("id参数有误");
            $("#tipModal").modal('show');
            return;
          }
          if (confirm("你确认删除该记录吗? \r\n 删除后再也不能找回，请谨慎操作！")) {
            $.ajax({
              type: 'post',
              url: "/admin/home/resource/deleteByStrategySeq",
              data: {
                seq: seq,
                partitionId: partitionId,
              },
              dataType: "json",
              success: function (json) {
                if (json.code == 200) {
                  $("#tipMsg").text("删除成功");
                  $("#tipModal").modal('show');
                  TableHelper.doRefresh("#table");
                } else {
                  $("#tipMsg").text("删除失败");
                  $("#tipModal").modal('show');
                }
              }
            });
          }
        });

        function apiResult (json) {
          if (json.code == 200 && json.message == 'success') {
            return true;
          }
          $("#tipMsg").text("请求失败，错误信息：" + json.message);
          $("#tipModal").modal('show');
          return false;
        }


        $('#iconBtnA').on('click', function () {
          if ($('#iconFileA').val() == '') {
            $('#tipMsg').text('上传图片为空');
            $('#tipModal').modal('show');
            return;
          }
          $.ajaxFileUpload({
            fileElementId: 'iconFileA',    //需要上传的文件域的ID，即<input type="file">的ID。
            url: '/admin/upload/img', //后台方法的路径
            type: 'post',   //当要提交自定义参数时，这个参数要设置成post
            dataType: 'json',   //服务器返回的数据类型。可以为xml,script,json,html。如果不填写，jQuery会自动判断。
            secureuri: false,   //是否启用安全提交，默认为false。
            async: true,   //是否是异步
            success: function (json) {   //提交成功后自动执行的处理函数，参数data就是服务器返回的数据。
              if (json.path) {
                $('#iconUrlA').val(json.path);
                $('#iconImgUrlA').attr("src", json.path);

                console.log(json.path);

              } else {
                $("#tipMsg").text(json.msg);
                $("#tipModal").modal('show');
              }
            },
            error: function (data, status, e) {  //提交失败自动执行的处理函数。
              console.error(e);
            }
          });
        })

        $('#iconBtnB').on('click', function () {
          if ($('#iconFileB').val() == '') {
            $('#tipMsg').text('上传图片为空');
            $('#tipModal').modal('show');
            return;
          }
          $.ajaxFileUpload({
            fileElementId: 'iconFileB',    //需要上传的文件域的ID，即<input type="file">的ID。
            url: '/admin/upload/img', //后台方法的路径
            type: 'post',   //当要提交自定义参数时，这个参数要设置成post
            dataType: 'json',   //服务器返回的数据类型。可以为xml,script,json,html。如果不填写，jQuery会自动判断。
            secureuri: false,   //是否启用安全提交，默认为false。
            async: true,   //是否是异步
            success: function (json) {   //提交成功后自动执行的处理函数，参数data就是服务器返回的数据。
              if (json.path) {
                $('#iconUrlB').val(json.path);
                $('#iconImgUrlB').attr("src", json.path);

                console.log(json.path);

              } else {
                $("#tipMsg").text(json.msg);
                $("#tipModal").modal('show');
              }
            },
            error: function (data, status, e) {  //提交失败自动执行的处理函数。
              console.error(e);
            }
          });
        });

        $("#resourceA").change(function () {
          var optVal = $(this).val();
          if (optVal != undefined && optVal == 5) {
            $('#contentA').val('');
            $('#contentLabA').html('网址链接<font color="red">*</font>:');

            $("#boxA").show();
          } else if (optVal != undefined && optVal == 6) {
            $('#contentA').val('');
            $('#contentLabA').html('房主平台号<font color="red">*</font>:');
            $("#boxA").show();
          } else {
            $('#contentA').val('');
            $("#boxA").hide();
          }

        });

        $("#resourceB").change(function () {
          var optVal = $(this).val();
          if (optVal != undefined && optVal == 5) {
            $('#contentB').val('');
            $('#contentLabB').html('网址链接<font color="red">*</font>:');

            $("#boxB").show();
          } else if (optVal != undefined && optVal == 6) {
            $('#contentB').val('');
            $('#contentLabB').html('房主平台号<font color="red">*</font>:');
            $("#boxB").show();
          } else {
            $('#contentB').val('');
            $("#boxB").hide();
          }

        });

        function pardeResourceType (val) {
          if (val == 1) {
            return '牌照房';
          } else if (val == 2) {
            return '相亲房';
          } else if (val == 3) {
            return 'PK房';
          } else if (val == 4) {
            return '游戏房';
          } else if (val == 5) {
            return 'H5';
          } else if (val == 6) {
            return '自定义房间';
          } else if (val == 7) {
            return '个播房';
          } else {
            return '';
          }
        }


        function clearModal () {
          $("#id").val('');

          $('#iconUrlA').val('');
          $('#iconImgUrlA').attr('src', '');
          $('#iconFileA').val('');

          $('#iconUrlB').val('');
          $('#iconImgUrlB').attr('src', '');
          $('#iconFileB').val('');

          $('#contentA').val('');
          $('#contentB').val('');


          $('#resourceA').val('');
          $('#resourceB').val('');

          $('#beginTime').val('');
          $('#endTime').val('');
        }

      });
    }
  },

};
</script>

<style scoped></style>