<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="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="dressType"
                     class="col-sm-3 control-label">装扮类型:</label>
              <div class="col-sm-9">
                <select name="dressType"
                        id="dressType">
                  <option value="">-- 请选择 --</option>
                  <option value="0">头饰</option>
                  <option value="1">座驾</option>
                  <option value="2">铭牌</option>
                  <option value="3">资料卡</option>
                  <option value="4">聊天气泡</option>
                </select>
              </div>
            </div>
            <div class="form-group"
                 id="txtBox">
              <label for="dressId"
                     class="col-sm-3 control-label">装扮id<font color="red">*</font>：</label>
              <div class="col-sm-9">
                <input type="text"
                       class="form-control validate[required]"
                       name="dressId"
                       id="dressId"
                       placeholder="请输入对应的装扮id">
              </div>
            </div>
            <div class="form-group">
              <label for="dressSeq"
                     class="col-sm-3 control-label">展示排序<font color="red">*</font>：</label>
              <div class="col-sm-9">
                <input type="text"
                       class="form-control validate[required]"
                       name="dressSeq"
                       id="dressSeq"
                       placeholder="数字小的排前面，必填">
              </div>
            </div>
            <div class="form-group">
              <label for="dressPrice"
                     class="col-sm-3 control-label">装扮价格:</label>
              <div class="col-sm-9">
                <input type="text"
                       class="form-control validate[required]"
                       name="dressPrice"
                       id="dressPrice"
                       placeholder="请输入价格">
              </div>
            </div>
            <div class="form-group">
              <label for="dressDay"
                     class="col-sm-3 control-label">有效期（天）:</label>
              <div class="col-sm-9">
                <input type="text"
                       class="form-control validate[required]"
                       name="dressDay"
                       id="dressDay"
                       placeholder="请输入天数">
              </div>
            </div>
            <div class="form-group">
              <label for="dressLimitStatus"
                     class="col-sm-3 control-label">装扮限时状态:</label>
              <div class="col-sm-9">
                <select name="dressType"
                        id="dressLimitStatus">
                  <option value="0">是</option>
                  <option value="1">否</option>
                </select>
              </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 } from '@/utils/maintainer';

export default {
  name: "DressShopAdminView",
  setup () {
    return {};
  },
  created () {
    this.$nextTick(function () {
      this.initData();
    });
  },
  methods: {
    initData () {
      $(function () {
        $('#table').bootstrapTable('destroy');
        $('#table').bootstrapTable({
          columns: [
            { field: 'id', title: 'ID', align: 'center', valign: 'middle', width: '10%' },
            { field: 'dressId', title: '装扮id', align: 'center', valign: 'middle', width: '10%' },
            { field: 'name.zh', title: '装扮名称', align: 'left', valign: 'middle', width: '10%' },
            { field: 'name.ar', title: '阿语装扮名称', align: 'left', valign: 'middle', width: '10%' },
            { field: 'name.en', title: '英语装扮名称', align: 'left', valign: 'middle', width: '10%' },
            { field: 'name.tr', title: '土耳其装扮名称', align: 'left', valign: 'middle', width: '10%' },
            {
              field: 'pic', title: '装扮图片', align: 'left', valign: 'middle', width: '10%',
              formatter: function (val, row, index) {
                if (null != val && val != '') {
                  return '<img src="' + val + '" alt="" style="width: 30px; height: 30px;">';
                }
                return '-';
              }
            },
            {
              field: 'dressType',
              title: '装扮类型',
              align: 'center',
              width: '5%',
              valign: 'middle',
              formatter: function (val, row, index) {
                if (val == '0') {
                  return "头饰";
                } else if (val == '1') {
                  return '座驾';
                } else if (val == '2') {
                  return '铭牌';
                } else if (val == '3') {
                  return '资料卡';
                } else if (val == '4') {
                  return '聊天气泡';
                } else {
                  return '-';
                }
              }

            },
            { field: 'dressSeq', title: '装扮排序', align: 'center', valign: 'middle', width: '10%' },
            { field: 'dressPrice', title: '装扮展示价值', align: 'center', valign: 'middle', width: '10%' },
            { field: 'dressDay', title: '装扮有效期（天）', align: 'center', valign: 'middle', width: '10%' },
            { field: 'buyNum', title: '购买数量', align: '购买数量   ', valign: 'middle', width: '10%' },
            { field: 'userDonateNum', title: '购买赠送用户数量', align: '购买数量', valign: 'middle', width: '10%' },
            {
              field: 'dressLimitStatus',
              title: '装扮限时状态',
              align: 'center',
              width: '5%',
              valign: 'middle',
              formatter: function (val, row, index) {
                if (val == '0') {
                  return "有效";
                } else {
                  return '无效';
                }
              }

            },
            {
              field: 'id',
              title: '操作',
              align: 'center',
              width: '10%',
              formatter: function (val, row, index) {
                return '<button id="btnEdit" name="btnEdit" class="btn btn-sm btn-success opt-edit" data-id=' + val + '>' +
                  '<i class="glyphicon glyphicon-edit"></i> 编辑</button>' +
                  '&nbsp;&nbsp;<button class="btn btn-sm btn-danger opt-remove" data-id=' + val + ' data-new-status=' + 2 +
                  '><i class="glyphicon glyphicon-remove"></i>删除</button>';

              }
            }
          ],
          undefinedText: "-",
          cache: false,
          striped: true,
          showRefresh: false,
          pageSize: 50,
          pagination: true,
          pageList: [20, 50, 100],
          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/dress/shop/list',
              contentType: 'application/json;charset=utf-8',
              dataType: 'json',
              data: request.data,
              success: function (res) {
                apiResult(res);
                console.log(res)
                request.success({
                  total: res.data.total,
                  rows: res.data.rows.map(i => {
                    let value = i.name;
                    if (value.startsWith('{') && value.endsWith('}')) {
                      i.name = JSON.parse(i.name);
                    } else {
                      i.name = {
                        zh: i.name,
                        ar: i.name,
                        en: i.name,
                      };
                    }
                    return i;
                  })
                });
              },
              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();
          $("#roomTagModal").modal('show');
        });

        $("#add").click(function () {
          var id = $("#id").val();
          var dressType = $('#dressType').val();
          var dressId = $("#dressId").val();
          var dressSeq = $('#dressSeq').val();
          var dressPrice = $('#dressPrice').val();
          var dressDay = $('#dressDay').val();
          var dressLimitStatus = $('#dressLimitStatus').val();

          if ($("#addForm").validationEngine('validate')) {
            $.ajax({
              type: "post",
              url: "/admin/dress/shop/saveOrUpdate",
              data: {
                id: id,
                dressId: dressId,
                dressType: dressType,
                dressSeq: dressSeq,
                dressPrice: dressPrice,
                dressDay: dressDay,
                dressLimitStatus: dressLimitStatus,
              },
              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 () {
          var id = $(this).attr("data-id");
          clearModal();

          $.ajax({
            type: "get",
            url: "/admin/dress/shop/getById",
            data: { id: id },
            dataType: "json",
            success: function (res) {
              var json = res.data;
              if (json) {
                $("#id").val(id);
                $('#dressId').val(json.dressId);
                $('#dressType').val(json.dressType);
                $('#dressSeq').val(json.dressSeq);
                $('#dressPrice').val(json.dressPrice);
                $('#dressDay').val(json.dressDay);
                $('#dressLimitStatus').val(json.dressLimitStatus);
                // 打开编辑弹窗
                $("#roomTagModal").modal('show');
                $("#modalLabel").text("编辑");
              } else {
                $("#tipMsg").text("获取信息出错");
                $("#tipModal").modal('show');
              }
            }
          });
        });

        $("#table").on("click", '.opt-remove', function () {
          var id = $(this).attr("data-id");

          if (confirm("你确认删除该记录吗? \r\n 删除后再也不能找回，请谨慎操作！")) {
            const requestParam = {
              id: id
            }

            $.ajax({
              type: "get",
              url: "/admin/dress/shop/delById",
              data: requestParam,
              dataType: "json",
              contentType: 'application/json',
              success: function (json) {
                if (json.code == 200) {
                  $("#tipMsg").text("修改成功");
                  $("#tipModal").modal('show');
                  TableHelper.doRefresh("#table");
                } else {
                  $("#tipMsg").text("修改失败." + json.message);
                  $("#tipModal").modal('show');
                }
              }
            });
          }
        });



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


        $('#iconBtn').on('click', function () {
          if ($('#iconFile').val() == '') {
            $('#tipMsg').text('上传图片为空');
            $('#tipModal').modal('show');
            return;
          }
          $.ajaxFileUpload({
            fileElementId: 'iconFile',    //需要上传的文件域的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) {
                $('#iconUrl').val(json.path);
                $('#iconImgUrl').attr("src", json.path);

                console.log(json.path);

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

        function clearModal () {
          $('#iconImgUrl').attr('src', '');

          $('#addForm').find('input[type=text],input[type=hidden],input[type=file]').each(function () {
            $(this).val('');
          })

          $('#type').val(1);

        }


        $("#type").change(function () {
          var optVal = $(this).val();
        });



      });
    }
  },

};
</script>

<style scoped></style>