<script>
    layui.use(['table', 'form', 'element', 'layer', 'Split', 'admin','index'], function () {
        let $ = layui.jquery;
        let Split = layui.Split;
        // 水平分割,需要分割的元素(id)、默认大小(百分比)、最小值(单位px)
        Split(['#s1', '#s2', '#s3', '#s4', '#s5', '#s6'], {sizes: [9, 12, 12, 12, 12, 43], minSize: 70});
        let table = layui.table;
        let form = layui.form;
        let index = layui.index;
        let admin = layui.admin;

        let initCondition = {source_type: 'all'};
        let whereCondition = initCondition;
        let type = 'all';
        let currentPage = 1;

        $('#refreshWindow').click(function () {
            //判断当前是否有layui弹窗窗口,有的话不刷新
            let hasLayerIframe = $('.layui-layer').size() > 0;
            if (!hasLayerIframe) {
                $('#getSupplierListButton').click();
            }
        });

        //点击罗盘筛选
        $('.main_filter').click(function () {
            clearTypeFilter();
            $(this).attr('class', 'main_filter layui-badge layui-bg-green');
            type = $(this).attr('id');
            whereCondition.source_type = type
            table.reload('list', {
                page: {
                    curr: 1
                }
                , where: whereCondition
            });
        });

        //多加了个区分根据状态去筛选
        $('.status_filter').click(function () {
            clearTypeFilter();
            $(this).attr('class', 'status_filter layui-badge layui-bg-green');
            type = $(this).attr('id');
            whereCondition.source_type = type
            //先清空状态
            whereCondition.status = 0;
            table.reload('list', {
                page: {
                    curr: 1
                }
                , where: whereCondition
            });
            let status = $(this).attr('data-value');
            //同时还要去联动下面的状态筛选
            $('#status').val(status);
            form.render('select')
        });

        let cols = [
            {type: 'checkbox', fixed: true},
            {field: 'supplier_id', title: '供应商ID', align: 'center', width: 80},
            {
                field: 'supplier_code', title: '供应商编码', align: 'center', width: 90, templet: function (data) {

                    return "<a ew-href='/supplier/SupplierDetail?view=iframe&supplier_id=" + data.supplier_id +
                        "' class='list-href' ew-title='供应商详情 - " + data.supplier_code + "'>" + data.supplier_code + "</a>"
                }
            },
            {
                field: 'supplier_name', title: '供应商名称', align: 'center', width: 180, templet: function (data) {
                    if (data.status === -3) {
                        return "<span title='" + data.block_reason + "'>" + data.supplier_name + "</span>"
                    } else {
                        return data.supplier_name;
                    }
                }
            },
            {field: 'supplier_group', title: '供应商性质', align: 'center', width: 115},
            {
                field: 'level', title: '等级', align: 'center', width: 60, templet: function (d) {
                    return d.level ? d.level : '-';
                }
            },
            {field: 'region_name', title: '区域', align: 'center', width: 60},
            {
                field: 'stockup_type', title: '合作类型', align: 'center', width: 120, templet: function (data) {
                    return "<span title='" + data.stockup_type + "'>" + data.stockup_type + "</span>"
                }
            },
            {
                field: 'quality_assurance_agreement',
                title: '品质协议',
                align: 'center',
                width: 80,
                templet: function (data) {
                    if (data.attachment) {
                        return data.attachment.quality_assurance_agreement ? '有' : '无';
                    }
                    return '无';
                }
            },
            {
                field: 'contact_num', title: '联系人', align: 'center', width: 70, templet: function (data) {
                    return "<a ew-href='/supplier/SupplierDetail?view=iframe&tab=contact&supplier_id=" + data.supplier_id +
                        "' class='list-href' ew-title='供应商详情 - " + data.supplier_code + "' title='点击跳转查看联系人列表'>" + data.contact_num + "</a>"
                }
            },

            {field: 'has_sku', title: 'SKU上传', align: 'center', width: 80},
            {
                field: 'uploaded_sku', title: 'SKU合作', align: 'center', width: 80, templet: function (data) {
                    return data.uploaded_sku > 0 ? '是' : '否';
                }
            },
            {
                field: 'status_name', title: '状态', align: 'center', width: 80, templet: function (data) {
                    if (data.status === 3) {
                        return "<span style='color: red' title='" + data.reject_reason + "'>" + data.status_name + "</span>"
                    } else if (data.status === -3) {
                        return "<span style='color: red' title='" + data.block_reason + "'>" + data.status_name + "</span>"
                    } else {
                        return data.status_name;
                    }
                }
            },
            {field: 'channel_username', title: '采购员', align: 'center', width: 130},
            {field: 'purchase_username', title: '渠道开发员', align: 'center', width: 110},
            {field: 'create_name', title: '创建人', align: 'center', width: 70},
            {field: 'update_time', title: '最近修改时间', align: 'center', width: 145},
            {field: 'supplier_type_name', title: '供应商类别', align: 'center', width: 110},
        ];

{{--        @if(checkPerm('ViewFakeSupplier') && request()->user->userId == 1000)--}}
{{--        cols.push({--}}
{{--            field: 'is_type', title: '正式供应商', align: 'center', width: 110, templet: function (data) {--}}
{{--                return data.is_type === 0 ? '正式' : '<span style="color: red">待转正</span>';--}}
{{--            }--}}
{{--        })--}}
{{--        @endif--}}
        cols.push(
            {field: 'create_time', title: '创建时间', align: 'center', width: 145},
        );
        table.render({
            elem: '#list'
            , url: '/api/supplier/GetSupplierList'
            , method: 'post'
            , size: 'sm'
            , limit: 20
            , cellMinWidth: 50 //全局定义常规单元格的最小宽度
            , where: whereCondition
            , loading: true
            , first: true //不显示首页
            , last: false //不显示尾页
            , cols: [cols]
            , id: 'list'
            , page: {}
            , done: function (res, curr, count) {
                //得到当前页码
                currentPage = curr;

                res.data.forEach(function (item, index) {
                    if (item.status === -3) {
                        //禁用复选框,设置不可选中标识,将该行设置为阴影色
                        var tr = $(".layui-table tr[data-index=" + index + "]");
                        tr.find("input[type='checkbox']").prop('disabled', true);
                        tr.find("input[type='checkbox']").next().addClass('layui-btn-disabled');
                        tr.find('.layui-form-checkbox').addClass('layui-hide');
                        tr.css("color", "#A9A5A5");
                        tr.addClass('block-class')
                    }

                });
            }
        });

        // 点击行checkbox选中
        $(document).on("click", ".layui-table-body table.layui-table tbody tr", function () {
            let index = $(this).attr('data-index');
            let tableBox = $(this).parents('.layui-table-box');
            let tableDiv = null;
            if (tableBox.find(".layui-table-fixed.layui-table-fixed-l").length > 0) {
                tableDiv = tableBox.find(".layui-table-fixed.layui-table-fixed-l");
            } else {
                tableDiv = tableBox.find(".layui-table-body.layui-table-main");
            }
            let checkCell = tableDiv.find("tr[data-index=" + index + "]").find("td div.laytable-cell-checkbox div.layui-form-checkbox I");
            if (checkCell.length > 0) {
                checkCell.click();
            }
        });

        $(document).on("click", "td div.laytable-cell-checkbox div.layui-form-checkbox", function (e) {
            e.stopPropagation();
        });

        //监听复选框事件,被选中的行高亮显示
        table.on('checkbox(list)', function (obj) {
            //拉黑就不用变色了
            if (obj.data.status === -3) {
                return
            }
            if (obj.checked === true && obj.type === 'all') {
                //点击全选,拉黑的不用选上
                $('.layui-table-body table.layui-table tbody tr:not(.block-class)').addClass('layui-table-click');
                $('.layui-table-body table.layui-table tbody').find('.block-class').find('.layui-form-checkbox').remove();
                $('.layui-table-body table.layui-table tbody tr .block-class').addClass('layui-table-click');
            } else if (obj.checked === false && obj.type === 'all') {
                //点击全不选
                $('.layui-table-body table.layui-table tbody tr').removeClass('layui-table-click');
            } else if (obj.checked === true && obj.type === 'one') {
                //点击单行
                if (obj.checked === true) {
                    obj.tr.addClass('layui-table-click');
                } else {
                    obj.tr.removeClass('layui-table-click');
                }
            } else if (obj.checked === false && obj.type === 'one') {
                //点击全选之后点击单行
                if (obj.tr.hasClass('layui-table-click')) {
                    obj.tr.removeClass('layui-table-click');
                }
            }
        });

        //保存需要刷新的页面数据
        function saveRefreshData(type, supplierId = 0) {
            admin.putTempData("needFreshDetail_supplier_id=" + supplierId, 1);
        }

        //新增供应商弹窗
        $("#add_supplier").click(function () {
            // layer.open({
            //     type: 2,
            //     content: '/supplier/AddSupplier?view=iframe',
            //     area: ['1000px', '97%'],
            //     title: '新增供应商',
            //     offset: ['10px'],
            //     end: function () {
            //         table.reload('list');
            //         supplierStatistics();
            //     }
            // });
            index.openTab({
                title: '新增供应商',
                url: '/supplier/AddSupplier?view=iframe',
                end: function() {
                    // insTb.reload();
                }
            });
        })

        //同步金蝶的手动操作
        $("#sync_supplier_to_erp").click(function () {
            let checkStatus = table.checkStatus('list');
            let data = checkStatus.data;
            if (!data.length) {
                layer.msg('请先选择要操作的供应商', {icon: 5})
            } else {
                if (data.length > 1) {
                    layer.msg('该操作不支持多选', {icon: 5})
                    return;
                }
                let supplierId = data[0].supplier_id;
                let res = ajax('/api/supplier/SyncToErp', {supplier_id: supplierId})
                if (res.err_code === 0) {
                    table.reload('list')
                    layer.closeAll();
                    layer.msg(res.err_msg, {icon: 6})
                } else {
                    layer.msg(res.err_msg, {icon: 5})
                }
            }
        });

        //审批供应商弹窗
        $("#audit_supplier").click(function () {
            let checkStatus = table.checkStatus('list');
            let data = checkStatus.data;
            if (!data.length) {
                layer.msg('请先选择要操作的供应商', {icon: 5})
            } else {
                if (data.length > 1) {
                    layer.msg('该操作不支持多选', {icon: 5})
                    return;
                }
                let supplierId = data[0].supplier_id;
                let status = data[0].status;
                let canReviewSupplier = {{checkPerm("ReviewSupplier")?1:0}};
                if (canReviewSupplier === 0 && status === -1) {
                    layer.msg('你没有复审供应商的权限', {icon: 5})
                    return
                }
                if (status === 0) {
                    layer.msg('该供应商还没有申请审核', {icon: 5});
                    return;
                }
                if (status !== 1 && status !== -1) {
                    layer.msg('该供应商已经被审核', {icon: 5});
                    return;
                }
                // if (status === -1) {
                //     layer.msg('要审核中的供应商才可以审核', {icon: 5});
                //     return
                // }
                let checkAuditMsg = checkCanAudit(supplierId);
                if (checkAuditMsg !== '') {
                    layer.msg(checkAuditMsg, {icon: 5});
                    return
                }
                layer.open({
                    type: 2,
                    content: '/supplier/AuditSupplier?view=iframe&supplier_id=' + supplierId,
                    area: ['800px', '65%'],
                    title: '审核供应商',
                    end: function () {
                        table.reload('list');
                        saveRefreshData('detail', supplierId)
                        supplierStatistics();
                    }
                });
            }
        })

        //批量修改(分配)渠道员
        $("#batch_allocate_purchase_user").click(function () {
            let checkStatus = table.checkStatus('list');
            let data = checkStatus.data;
            let supplierIds = Array.from(data, ({supplier_id}) => supplier_id);
            supplierIds = supplierIds.join(',');
            if (!data.length) {
                layer.msg('请先选择要操作的供应商', {icon: 5})
            } else {
                let status = Array.from(data, ({status}) => status);
                //分配采购员的多选操作,需要先去判断是否存在审核中的供应商,存在的话,要提示
                if (status.indexOf(1) !== -1 || status.indexOf(-3) !== -1 || status.indexOf(-1) !== -1) {
                    layer.msg('选择的供应商里,存在审核中/待复审/黑名单的供应商,无法分配渠道员', {icon: 5})
                    return
                }
                layer.open({
                    type: 2,
                    content: '/supplier/BatchAllocatePurchaseUser?view=iframe&supplier_ids=' + supplierIds,
                    area: ['600px', '70%'],
                    title: '批量分配渠道员',
                    end: function () {
                        table.reload('list');
                        supplierStatistics();
                    }
                });
            }
        })

        //申请进入审核中的状态
        $("#batch_apply_in_review_supplier").click(function () {
            let checkStatus = table.checkStatus('list');
            let data = checkStatus.data;
            let supplierIds = Array.from(data, ({supplier_id}) => supplier_id);
            supplierIds = supplierIds.join(',');
            if (!data.length) {
                layer.msg('请先选择要操作的供应商', {icon: 5})
            } else {
                let status = Array.from(data, ({status}) => status);
                let canApplyInReview = true;
                $.each(status, function (index, value) {
                    if (value !== 0) {
                        canApplyInReview = false;
                    }
                });
                if (!canApplyInReview) {
                    layer.msg('选择的供应商里,存在非待审核状态的供应商,无法申请审核', {icon: 5})
                    return false;
                }
                //还要去事先检测供应商信息是否完整
                let checkApplyMsg = checkCanApplyInReview(supplierIds);
                if (checkApplyMsg !== '') {
                    layer.msg(checkApplyMsg, {icon: 5});
                    return
                }
                layer.open({
                    type: 2,
                    content: '/supplier/BatchApplyInReviewSupplier?view=iframe&supplier_ids=' + supplierIds,
                    area: ['800px', '70%'],
                    title: '批量申请审核供应商',
                    end: function () {
                        table.reload('list');
                        supplierStatistics();
                    }
                });
            }
        })


        //分配采购员
        $("#allocate_channel_user").click(function () {
            let checkStatus = table.checkStatus('list');
            let data = checkStatus.data;
            if (!data.length) {
                layer.msg('请先选择要操作的供应商', {icon: 5})
            } else {
                if (data.length > 1) {
                    layer.msg('该操作不支持多选', {icon: 5})
                    return;
                }
                const status = data[0].status;
                if ((status !== -1 || status !== 1)) {
                    let supplierId = data[0].supplier_id;
                    layer.open({
                        type: 2,
                        content: '/supplier/AllocateChannelUser?view=iframe&supplier_id=' + supplierId,
                        area: ['650px', '80%'],
                        title: '新增采购员',
                        end: function () {
                            saveRefreshData('detail', supplierId)
                            table.reload('list');
                            supplierStatistics();
                        }
                    });
                } else {
                    layer.msg('审核中/待复审状态的供应商无法分配采购员', {icon: 5})
                    return false;
                }

            }
        })

        //禁用供应商
        $("#disable_supplier").click(function () {
            let checkStatus = table.checkStatus('list');
            let data = checkStatus.data;
            if (!data.length) {
                layer.msg('请先选择要操作的供应商', {icon: 5})
            } else {
                if (data.length > 1) {
                    layer.msg('该操作不支持多选', {icon: 5})
                    return;
                }
                const status = data[0].status;
                const hasSku = data[0].sku_num;
                const needReview = data[0].need_review;
                if (needReview === 1 && status !== 0) {
                    layer.msg("该供应商还没有进行复审,不能直接禁用;", {icon: 5})
                    return;
                }
                if ((status === 3 || status === 2 || status === 0) && !hasSku) {
                    layer.confirm('确定要禁用该供应商吗?', function (index) {
                        let supplierId = data[0].supplier_id;
                        let res = ajax('/api/supplier/DisableSupplier', {supplier_id: supplierId})
                        if (res.err_code === 0) {
                            saveRefreshData('detail', supplierId)
                            table.reload('list')
                            supplierStatistics();
                            layer.closeAll();
                            layer.msg(res.err_msg, {icon: 6})
                        } else {
                            layer.msg(res.err_msg, {icon: 5})
                        }
                    });
                } else {
                    layer.msg('只有待审核,已通过或者未通过状态,并且没有sku的供应商才可以禁用', {'icon': 5});
                }

            }
        });
        //转正供应商
        $("#change_supplier_is_type").click(function () {
            let checkStatus = table.checkStatus('list');
            let data = checkStatus.data;
            if (!data.length) {
                layer.msg('请先选择要操作的供应商', {icon: 5})
            } else {
                if (data.length > 1) {
                    layer.msg('该操作不支持多选', {icon: 5})
                    return;
                }
                const isType = data[0].is_type;
                if (isType === 0) {
                    layer.msg('该供应商已经是正式供应商', {'icon': 5});
                    return
                }
                layer.confirm('如果转成正式供应商,会进入审核中状态,需要补全相关信息申请审核,确定要转正该供应商吗?', function (index) {
                    let supplierId = data[0].supplier_id;
                    let res = ajax('/api/supplier/ChangeSupplierIsType', {supplier_id: supplierId, is_type: 0})
                    if (res.err_code === 0) {
                        saveRefreshData('detail', supplierId)
                        table.reload('list')
                        supplierStatistics();
                        layer.closeAll();
                        layer.msg(res.err_msg, {icon: 6})
                    } else {
                        layer.msg(res.err_msg, {icon: 5})
                    }
                });
            }
        });
        //加入黑名单
        $("#block_supplier").click(function () {
            let checkStatus = table.checkStatus('list');
            let data = checkStatus.data;
            if (!data.length) {
                layer.msg('请先选择要操作的供应商', {icon: 5})
            } else {
                if (data.length > 1) {
                    layer.msg('该操作不支持多选', {icon: 5})
                    return;
                }
                const status = data[0].status;
                if (status === -3) {
                    layer.msg('该供应商已经在黑名单', {icon: 5});
                    return false;
                }
                if ((status === -1 || status === 1)) {
                    layer.msg('审核中/待复审状态的供应商无法加入黑名单', {icon: 5});
                    return false;
                } else {
                    let supplierId = data[0].supplier_id;
                    layer.open({
                        type: 2,
                        content: '/supplier/BlockSupplier?view=iframe&supplier_id=' + supplierId,
                        area: ['700px', '70%'],
                        title: '加入黑名单',
                        end: function () {
                            saveRefreshData('detail', supplierId)
                            table.reload('list');
                            supplierStatistics();
                        }
                    });
                }
            }
        });

        //共用供应商申请
        $("#apply_supplier_share").click(function () {
            layer.open({
                type: 2,
                content: '/supplier_share_apply/ApplySupplierShare?view=iframe',
                area: ['700px', '80%'],
                title: '申请共用供应商',
                end: function () {
                }
            });
        });
        //共用供应商审核
        $("#audit_supplier_share_apply").click(function () {
            layer.open({
                type: 2,
                content: '/supplier_share_apply/AuditSupplierShareApply?view=iframe',
                area: ['70%', '80%'],
                title: '共用申请审核',
                end: function () {
                }
            });
        });

        //点击查询按钮
        form.on('submit(load)', function (data) {
            //罗盘选项会跳回全部
            clearTypeFilter();
            $('#total').attr('class', 'status_filter layui-badge layui-bg-green');
            whereCondition.source_type = 'all';
            initCondition.source_type = whereCondition.source_type;
            whereCondition = $.extend(false, initCondition, data.field);
            //执行重载
            table.reload('list', {
                page: {
                    curr: 1
                }
                , where: whereCondition
            });
            supplierStatistics();
            return false;
        });

        //点击重置按钮
        form.on('submit(reset)', function (data) {
            layer.load(1);
            location.reload();
        });
    });

    //检查是否能够审核,因为审核人只能审自己相关部门人员修改的供应商记录
    function checkCanAudit(supplierId) {
        let url = '/api/supplier/CheckCanAuditSupplier?supplier_id=' + supplierId;
        let res = ajax(url);
        if (res.err_code !== 0) {
            return res.err_msg;
        } else {
            return '';
        }
    }

    function checkCanApplyInReview(supplierIds) {
        let url = '/api/supplier/CheckCanApplyInReview?supplier_ids=' + supplierIds;
        let res = ajax(url);
        if (res.err_code !== 0) {
            return res.err_msg;
        } else {
            return '';
        }
    }

    function clearTypeFilter() {
        $('.main_filter').attr('class', 'main_filter');
        $('.status_filter').attr('class', 'status_filter');
    }
</script>