{% extends 'obj_form.html' %}
{% load i18n %}


{% block subtitle %}
<ol class="breadcrumb">
    <li>{% trans '经销商管理' %}</li>
    <li>{% trans '下级转移' %}</li>
</ol>
{% endblock %}

{% block form_content %}
<script>

    $(document).ready(function () {

        $('#id_company_name').autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '/obj/ajax/autocomplete/agent/',
                    dataType: "json",
                    data: {
                        term: $("#id_company_name").val()
                    },
                    success: function (data) {
                        response(data);
                    }

                });
            },
            select: function (event, ui) {
                $("#id_company").val(ui.item.value);
                $("#id_company_name").val(ui.item.label);
                getChildren(ui.item.value)
                return false;
            }
        });

        $('#id_to_company_name').autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '/obj/ajax/autocomplete/agent/',
                    dataType: "json",
                    data: {
                        term: $("#id_to_company_name").val()
                    },
                    success: function (data) {
                        response(data);
                    }

                });
            },
            select: function (event, ui) {
                $("#id_to_company").val(ui.item.value);
                $("#id_to_company_name").val(ui.item.label);
                return false;
            }
        });

        var table

        function getChildren(company_id) {
            $.ajax({
                url: '/company/ajax/get_company_children/',
                data: {
                    company_id
                },
                success: function (res) {
                    if (res.e === '') {
                        var d = res.list.map(function (item) {
                            return [
                                `<input class="checkchild" value="${item.id}" type="checkbox">`,
                                item.name,
                                // item.external_code,
                                // item.level,
                                item.address,
                                item.cell_phone,
                                item.contacts,
                                `<div class='btn btn-danger btn-xs btn-del'>删除</div>`
                            ]
                        })
                        if (table) {
                            table.destroy()
                        }
                        if (d.length) {
                            $("#div_tb").show()
                            loadTable(d)
                        }
                        else {
                            $("#div_tb").hide()
                        }
                    }
                },
                error: function () {

                }
            })
        }

        function loadTable(data) {
            var page_length = 10;
            table = $('#tb').DataTable({
                dom: 'Bfrtip',
                autoWidth: true,
                pageLength: page_length,
                buttons: [{ extend: 'excelHtml5', text: '导出到Excel' }],
                language: lng,
                data: data,
            });
            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();
                    }
                });
            });
        }

        $('#tb tbody').on('click', '.btn-del', function (event) {
            table.row($(this).parents('tr')).remove().draw();
        });

        var del_trs = {}
        $("#tb").on('click', '.checkchild', function (e) {
            var check = $(this).prop("checked");
            var tr = $(this).parents('tr')
            var id = $(this).val()
            if (check) {
                if (!del_trs[id]) {
                    del_trs[id] = tr
                }
            }
            else {
                if (del_trs[id])
                    delete del_trs[id]
            }
        })

        $("#btn-delete-all").click(function () {
            console.log(del_trs)
            for (const item in del_trs) {
                table.row(del_trs[item]).remove().draw();
            }
            del_trs = {}
        })

        $(".checkall").on('click', function () {
            var list_before = $('.checkchild')
            for (var i = 0; i < list_before.length; i++) {
                if (list_before[i].checked) {
                    $(".checkchild").prop("checked", false);
                    break;
                } else {
                    $(".checkchild").prop("checked", true);
                    break;
                }
            }
            var list = $('.checkchild')
            for (var i = 0; i < list.length; i++) {
                var id = $(list[i]).val()
                var tr = $(list[i]).parents('tr')
                if (list[i].checked) {
                    if (!del_trs[id]) {
                        del_trs[id] = tr
                    }
                }
                else {
                    if (del_trs[id])
                        delete del_trs[id]
                    $(".checkchild").prop("checked", false);
                }
            }
        });

        $(".btn-next").click(function () {
            var arr = []
            table.rows().every(function (rowIdx, tableLoop, rowLoop) {
                var tr = this.node()
                var id = $(tr).find('.checkchild').val()
                var name = $(tr).children().eq(1).text()
                arr.push({
                    id,
                    name
                })
            });
            if (!$("#id_to_company").val()) {
                alert('请选择要转移的经销商')
                return
            }

            if ($("#id_to_company").val() == $("#id_company").val()) {
                alert('不能转移给自己')
                return
            }
            if (arr.length) {
                $("#confirm_agents").text(arr.map(function (item) { return item.name }).join('，'))
                $("#input_ids").val(arr.map(function (item) { return item.id }).join(','))
                $('#confirm_modal').modal('show')
                $("#warn").text(`请再次确认转移方向： ${$("#id_company_name").val()} ----> ${$("#id_to_company_name").val()}`)
            }
        })

        $("#btn_confirm").click(function () {
            var r = confirm('您确认要转移吗？')
            if (!r) return
            var ids = $("#input_ids").val()
            var company_id = $("#id_company").val()
            var to_company_id = $("#id_to_company").val()
            $.ajax({
                url: '/company/children_move/',
                method: 'post',
                data: {
                    ids,
                    company_id,
                    to_company_id
                },
                success: function (res) {
                    if (res.e === '') {
                        $('#confirm_modal').modal('hide')
                        $(".modal-backdrop").remove()
                        toastr.success("转移成功", "成功：",
                            { timeOut: 800, positionClass: "toast-center-center" }
                        );
                        $.RefreshContent('/company/children_move/');
                    }
                    else {
                        toastr.error(res.e, "操作错误：",
                            { timeOut: 800, positionClass: "toast-center-center" }
                        );
                    }
                },
                error: function () {
                    toastr.error("网络超时，请稍后再试", "操作错误：",
                        { timeOut: 800, positionClass: "toast-center-center" }
                    );
                }
            })
            console.log(ids, company_id, to_company_id)
        })

    })

</script>
<style>
    input[type=checkbox] {
        display: inline-block;
        width: auto;
        height: auto;
        margin-top: 10px;
    }
</style>
<input type="hidden" id="input_ids">

<div class="alert alert-success" role="alert" style="display: none">保存成功！</div>
<div>

    <div class="alert alert-info" role="alert">请输入公司名称并选择要转移的经销商，待列表数据加载后，选择删除不转移的经销商，之后选择下一步进行转移</div>
    <div>

        <div class="form-group" style="margin-bottom: 30px;">
            <div class="col-sm-6">
                <input id='id_company_name' class='form-control' placeholder="请输入公司名称" />
                <input id="id_company" name="company_id" type="hidden" />
            </div>
            <div class="col-sm-6">
                <input id='id_to_company_name' class='form-control' placeholder="请输入转移后经销商名称" />
                <input id="id_to_company" name="to_company_id" type="hidden" />
            </div>
        </div>

        <div class='col-md-12 form-group' id="div_tb" style="display: none; margin-bottom: 30px;">
            <div class="table-responsive">
                <table id='tb' class="table table-striped table-bordered dt-responsive nowrap tb" cellspacing="0"
                    width="100%">
                    <thead>
                        <tr>
                            <th>
                                <input type="checkbox" class="checkall" id="group_checkbox" style="display: none" />
                                <label for="group_checkbox">全选/反选
                                </label>
                            </th>
                            <th>名称</th>
                            <!-- <th>外部编码</th> -->
                            <!-- <th>营销层级</th> -->
                            <th>地址</th>
                            <th>联系电话</th>
                            <th>联系人</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>

                    </tbody>
                    <tfoot>
                        <th> <span class="btn btn-sm btn-danger" id="btn-delete-all">批量删除</span> </th>
                        <th><input type="text" placeholder="名称"></th>
                        <!-- <th><input type="text" placeholder="外部编码"></th> -->
                        <!-- <th><input type="text" placeholder="营销层级"></th> -->
                        <th><input type="text" placeholder="地址"></th>
                        <th><input type="text" placeholder="联系电话"></th>
                        <th><input type="text" placeholder="联系人"></th>
                        <th><input type="text" placeholder="操作"></th>
                    </tfoot>
                </table>
            </div>
        </div>

    </div>

    <div>
        <a class="btn btn-primary btn-next" type="button" style="float:right;">下一步</a>
    </div>
</div>

<div class="modal fade" tabindex="-1" role="dialog" id="confirm_modal">
    <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">转移确认</h4>
            </div>
            <div class="modal-body">
                <div class="alert alert-danger" role="alert" id="warn"></div>
                <div class="panel panel-primary">
                    <div class="panel-heading">
                        <h3 class="panel-title">待转移经销商</h3>
                    </div>
                    <div class="panel-body">
                        <p id="confirm_agents"></p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" id="btn_confirm">确定</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

{% endblock %}