{% load i18n %}

<script type="text/javascript">
  $(document).ready(function () {
    $('.datepicker').datepicker({ dateFormat: 'yy-mm-dd' });
    $('.datepicker').datepicker('setDate', new Date());
    setDatePickerZh();
    var order_id = 0;
    var order_code = '';

    $('#dt_fr').val('{{date_from}}');
    $('#dt_to').val('{{date_to}}');

    $('.btn-qry').click(function () {
      var date_from, date_to;
      date_fr = $('#dt_fr').val();
      date_to = $('#dt_to').val();
      var params = [];
      if (date_fr != '') { params.push('date_from=' + date_fr) };
      if (date_to != '') { params.push('date_to=' + date_to) };

      if (params.length == 0) {
        toastr.error("{% trans '请先输入查询条件！'%}", "{% trans '操作错误：'%}")
      } else {
        $.RefreshContent('{{request.path}}?' + params.join('&'));
      }
    });

    function label_pkg_to_name(label_pkg) {
      if (label_pkg == 1) {
        return '瓶'
      } else if (label_pkg == 2) {
        return '盒'
      } else if (label_pkg == 3) {
        return '箱'
      } else {
        return '/'
      }
    }

    //按产品统计 显示报表
    function show_product_tb(labels) {
      var product_tb_data = [];
      if (labels.length) {
        // 创建用于统计的 Map
        let productMap = new Map(); // 用于存储产品数据的 Map

        labels.forEach((item) => {
          let productName = item.product_name; // 产品名称
          let supplierName = item.supplier_name; // 供应商名称
          let labelPkg = label_pkg_to_name(item.label_pkg); // 转换规格为可读名称

          // 如果产品不存在于 Map 中，初始化
          if (!productMap.has(productName)) {
            productMap.set(productName, {
              supplier: supplierName,
              categories: {},
            });
          }

          // 更新规格数量
          let category = productMap.get(productName).categories;
          category[labelPkg] = (category[labelPkg] || 0) + 1;
        });

        // 转换 Map 数据为表格所需格式
        productMap.forEach((data, productName) => {
          const { supplier, categories } = data;

          for (let labelPkg in categories) {
            product_tb_data.push([supplier, productName, labelPkg, categories[labelPkg]]);
          }
        });


        $('#product_tb').DataTable({
          //"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
          //"bLengthChange":true,
          dom: 'Bfrtip',
          autoWidth: false,
          destroy: true,
          buttons: [{ extend: 'excelHtml5', text: '导出到Excel' }],
          language: lng,
          data: product_tb_data
        });
      }
    }

    //显示门店信息
    function show_agent_info(callon_data) {
      const {
        id, agent_name, cert_type_name, cert_no, address, contacts,
        cell_phone, tm, salesman_name, salesman_zh, signboard_img,
        salesdivision_name, subsaldivision_name, adm_name, level_name,
        channel_name, channel_level, serie,
        name, contact, phone, remark
      } = callon_data;
      $('#callon #callon_id').text(`盘点单号: ${id}`);
      $('#callon #agent_name').text(`门店名称：${agent_name}`);
      $('#callon #cert_type_name').text(`证书类型：${cert_type_name}`);
      $('#callon #cert_no').text(`证书编号：${cert_no}`);
      $('#callon #contacts').text(`门店联系人：${contacts}`);
      $('#callon #cell_phone').text(`门店联系方式：${cell_phone}`);
      $('#callon #tm').text(`盘点时间：${tm}`);
      $('#callon #salesman_name').text(`业务员：${salesman_name}`);
      $('#callon #salesman_zh').text(`业务员账号：${salesman_zh}`);

      // $('#callon #signboard_img').src(`${signboard_img}`);
      $('#callon #signboard_img').attr('src', `${signboard_img}`);

      $('#callon #salesdivision_name').text(`所属战区: ${salesdivision_name}`);
      $('#callon #subsaldivision_name').text(`分区: ${subsaldivision_name}`);
      $('#callon #adm_name').text(`销售区域: ${adm_name}`);
      $('#callon #channel_name').text(`渠道类型: ${channel_name}`);

      $('#callon #level_name').text(`发货层级: ${level_name}`);
      $('#callon #serie').text(`营销品种: ${serie}`);
      $('#callon #channel_level').text(`初评等级: ${channel_level}`);//渠道等级

      $('#callon #name').text(`门店拟更名为: ${name || '/'}`);
      $('#callon #contact').text(`门店联系人拟更名为: ${contact || '/'}`);
      $('#callon #phone').text(`门店联系方式拟更为: ${phone || '/'}`);
      $('#callon #remark').text(`门店信息修改意见、其他营销品种补充: ${remark}`);

    }
    //点击详情
    $('#tb').on("click", "td .details", function (event) {
      console.log('event', event);
      var callon_id = event.currentTarget.dataset.id * 1;
      var index = event.currentTarget.dataset.index * 1;
      // var callon_tb_data={{ data|safe }};
      // console.log('index', callon_tb_data[index])

      $.ajax({
        type: 'GET',
        // processData: false,
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        url: "/company/ajax/agent/tease/",
        data: {
          id: callon_id
        },
        success: function (res) {
          console.log('data-----', res);
          const { labels, callon_data, remark } = res
          show_agent_info(callon_data)
          $('#modal_review #remark').val(remark.join('\n'));
          var tease_tb_data = [];
          if (labels.length) {
            labels.sort(function (a, b) { return a.supplier_id - b.supplier_id });
            show_product_tb(labels)
            labels.forEach((item) => {
              tease_tb_data.push([item.supplier_name, item.label_code, item.product_name, label_pkg_to_name(item.label_pkg), item.tm]);
            })
          }
          $('#tease_tb').DataTable({
            //"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
            //"bLengthChange":true,
            dom: 'Bfrtip',
            autoWidth: false,
            destroy: true,
            buttons: [{ extend: 'excelHtml5', text: '导出到Excel' }],
            language: lng,
            data: tease_tb_data
          });
          $('#modal_review').modal('show')
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          alert('连接服务器失败');
          return;
        }
      });
    })

    $('#tb').on("click", "td a.btn-close-order", function (event) {
      event.preventDefault();
      order_id = $(this).attr('order_id');
      order_code = $(this).attr('code');
      $("#modal_permit").modal('show')
      return;
      $.OpenCfmDlg("{% trans '关闭订单' %}", "确定订单" + order_code + "已完成，要关闭此订单吗？");
    });

    $('#btn_save').click(function () {
      //$('#confirm-modal').modal('hide'); 
      var state = $("input[name='state']:checked").val();
      var voucher_code = $("#inputSaleOrderNumber").val();
      var remark = $("#inputRemark").val();
      console.log(state, voucher_code, remark);
      if (!state) {
        alert('请选择审核状态');
        return;
      }
      //return;
      $.ajax({
        type: 'POST',
        url: '/company/close/agent/order/' + order_id + '/',
        data: {
          state,
          voucher_code,
          remark
        },
        success: function (data) {
          if (data.cnt > 0) {
            $('#modal_permit').modal('hide');
            toastr.success("{% trans '订单' %}" + order_code + "{% trans '已关闭' %}", "{% trans '关闭订单完成：' %}",
              { timeOut: 2000, positionClass: "toast-center-center" });
            var date_from, date_to;
            date_fr = $('#dt_fr').val();
            date_to = $('#dt_to').val();
            var params = [];
            if (date_fr != '') { params.push('date_from=' + date_fr) };
            if (date_to != '') { params.push('date_to=' + date_to) };
            if (params.length == 0) {
              toastr.error("{% trans '请先输入查询条件！'%}", "{% trans '操作错误：'%}")
            } else {
              $.RefreshContent('{{request.path}}?' + params.join('&'));
            }
          } else {
            alert('订单关闭失败');

          };
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          alert('连接服务器失败');

        }
      });
    });


    var table = $('#tb').DataTable({
      dom: 'Bfrtip',
      autoWidth: true,
      buttons: [{ extend: 'excelHtml5', text: '导出到Excel' }],
      language: lng,
      data: {{ data| safe}}
        });
  table.columns().every(function () {
    var that = this;
    $('input', this.footer()).on('keyup change clear', function () {
      if (that.search() !== this.value) {
        that.search(this.value).draw();
      }
    });
  });          
       
    });

  function viewDetail(id) {
    $('#modal_review').modal('show')
    $.ajax({
      type: 'GET',
      processData: false,
      contentType: 'application/json; charset=utf-8',
      url: "/company/list/agent/order/" + id + "/",
      success: function (html) {
        $("#review_body").html(html);
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert('连接服务器失败');
        return;
      }
    });
  }

</script>



<ol class="breadcrumb">
  <li>{{subtt.0}}</li>
  <li>{{subtt.1}}</li>
</ol>




<div class='col-sm-12 form-inline' style='margin-bottom:20px;'>
  <div class="col-sm-3 input-group">
    <span class="input-group-addon">{% trans "开始日期"%}</span>
    <input class="datepicker form-control" id="dt_fr" />
  </div>
  <div class="col-sm-3 input-group">
    <span class="input-group-addon">{% trans "结束日期"%}</span>
    <input class="datepicker form-control" id="dt_to" />
  </div>
  <div style="float:right;">
    <span class='input-group-btn'>
      <a type="button" class='btn btn-primary btn-qry'>
        <span class='glyphicon glyphicon-search' style='padding-right:5px;'></span>{% trans '查找' %}
      </a>
    </span>
  </div>
</div>





<div class="col-md-12 col-sm-12 col-xs-12">
  <div class="x_panel">
    <div class="table-responsive">

      <table id='tb' class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
        <thead>
          {% for c in clmns %}
          <th>{{c}}</th>
          {% endfor %}
        </thead>
        <tbody></tbody>
        <tfoot>
          {% for c in clmns %}
          <th><input type="text" placeholder="{{c}}"></th>
          {% endfor %}
        </tfoot>
      </table>
    </div>
  </div>
</div>

<style>
  .modal-dialog {
    width: 70%;
  }

  #modal_review .title {
    text-align: left;
    font-size: 14px;
    font-weight: 600;
    line-height: 3;
  }

  #modal_review textarea {
    width: 100%;
  }

  .tease_tb_wrapper {
    margin-top: 50px;
  }

  #callon .info_box span {
    display: inline-block;
    width: 24%;
    height: 30px;
    vertical-align: top;
  }
</style>

<div class="modal fade" tabindex="-1" role="dialog" id="modal_review">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">盘库详情</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
            aria-hidden="true">&times;</span>
        </button>

        <div id='callon'>
          <div class="title">门店基础信息</div>
          <div class="info_box">
            <span id='callon_id'>盘点单号：</span>
            <span id='agent_name'>门店名称:</span>
            <span id='cert_type_name'>证书类型：</span>
            <span id='cert_no'>证书号：</span>
            <span id='adress'>地址：</span>
            <span id='contacts'>门店联系人：</span>
            <span id='cell_phone'>联系电话：</span>
            <span id="tm">盘点时间：</span>
            <span id="salesman_name">业务员：</span>
            <span id="salesman_zh">业务员账号：</span>
          </div>

          <div class="title">门头照片</div>
          <img id="signboard_img" src="" alt="" style="width: 200px;">

          <div class="title">门店销售信息</div>
          <div class="info_box">
            <span id='salesdivision_name'>所属战区：</span>
            <span id='subsaldivision_name'>分区:</span>
            <span id='adm_name'>销售区域：</span>
            <span id='channel_name'>渠道类型：</span>
            <span id='level_name'>发货层级：</span>
            <span id='serie'>营销品种：</span>
            <span id='channel_level'>初评等级：</span>
            <span id="name">门店拟更名为：</span>
            <span id="contact">门店联系人拟更为：</span>
            <span id="phone">联系方式拟更为：</span>
            <span id="remark">门店信息修改意见、其他营销品种补充:：</span>
          </div>
        </div>
      </div>
      <div class="modal-body">
        <table id="product_tb" class="table table-striped table-bordered dt-responsive" width="100%">
          <caption style="caption-side: top; font-size: 16px; font-weight: bold; text-align: center;">
            按产品分类统计表
          </caption>
          <thead>
            <tr>
              <th>供应商</th>
              <th>产品</th>
              <th>码类型</th>
              <th>数量</th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
        <table id="tease_tb" class="table table-striped table-bordered dt-responsive" width="100%"
          style="margin-top: 100px;">
          <caption style="caption-side: top; font-size: 16px; font-weight: bold; text-align: center;">
            汇总表
          </caption>
          <thead>
            <tr>
              <th>供应商</th>
              <th>码值</th>
              <th>产品</th>
              <th>码类型</th>
              <th>时间</th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>
      </div>
      <div style="padding: 20px;">
        <div class="title">无码盘库信息:</div>
        <textarea name="" id="remark"></textarea>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->




<div class="modal fade" id="modal_permit" tabindex="-1" role="dialog">
  <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>
      </div>
      <div class="modal-body" id="permit_body">

        <label class="control-label"><b>审核状态</b></label>
        <div>
          <span class="control-label"><input type="radio" name="state" class="" value="1" /> 通过</span>
          <span class="control-label"><input type="radio" name="state" class="" value="2" /> 驳回</span>
        </div>

        <label for="inputSaleOrderNumber" class="control-label" style="margin-top:5px"><b>销售单号</b></label>
        <input id="inputSaleOrderNumber" name="name" type="text" class="form-control" placeholder="输入销售单号"
          maxlength="50" />

        <label for="inputRemark" class="control-label" style="margin-top:5px"><b>备注</b></label>
        <input id="inputRemark" name="name" type="text" class="form-control" placeholder="输入备注" maxlength="50" />
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
        <button type="button" class="btn btn-primary" id="btn_save">保存</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->