<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('师傅列表')" />
    <th:block th:include="include :: layout-latest-css" />
    <th:block th:include="include :: ztree-css" />
</head>
<body class="gray-bg">

<div class="ui-layout-center">
    <div class="container-div">
        <div class="row">
            <div class="col-sm-12 search-collapse">
                <form id="user-form">
                    <div class="select-list">
                        <ul>
                            <li>
                                师傅名称：<input type="text" name="name"/>
                            </li>
                            <li>
                                手机号码：<input type="text" name="phone"/>
                            </li>
                            <li>
                                公司归属：<input type="text" name="deptName"/>
                            </li>
                            <li>
                                用户状态：<select name="status" th:with="type=${@dict.getType('sys_normal_disable')}">
                                <option value="">所有</option>
                                <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
                            </select>
                            </li>
                            <li class="select-time">
                                <label>创建时间： </label>
                                <input type="text" class="time-input" id="startTime" placeholder="开始时间" name="params[beginTime]"/>
                                <span>-</span>
                                <input type="text" class="time-input" id="endTime" placeholder="结束时间" name="params[endTime]"/>
                            </li>
                            <li>
                                服务区域：
                                <select name="provinceId" id="provinceId" onchange="areaChange(this, 'cityId')">
                                    <option value="">所有省份</option>
                                </select>
                                <select name="cityId" id="cityId" onchange="areaChange(this, 'districtId')">
                                    <option value="">所有城市</option>
                                </select>
                                <select name="districtId" id="districtId" onchange="areaChange(this, 'streetId')">
                                    <option value="">所有区县</option>
                                </select>
                                <select name="streetId" id="streetId">
                                    <option value="">所有街道</option>
                                </select>
                            </li>
                            <li>
                                服务技能：
                                <select name="categoryLevel1" id="categoryLevel1" onchange="categoryChange(this, 'categoryLevel2')">
                                    <option value="">所有类目</option>
                                </select>
                                <select name="categoryLevel2" id="categoryLevel2" onchange="categoryChange(this, 'categoryLevel3')">
                                    <option value="">二级类目</option>
                                </select>
                                <select name="goodsCategoryId" id="categoryLevel3">
                                    <option value="">三级类目</option>
                                </select>
                            </li>
                            <li>
                                <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i class="fa fa-search"></i>&nbsp;搜索</a>
                                <a class="btn btn-warning btn-rounded btn-sm" onclick="$.form.reset()"><i class="fa fa-refresh"></i>&nbsp;重置</a>
                            </li>
                        </ul>
                    </div>
                </form>
            </div>

            <div class="btn-group-sm" id="toolbar" role="group">
                <!-- <a class="btn btn-danger multiple disabled" onclick="$.operate.removeAll()" shiro:hasPermission="worker:worker:remove">
                    <i class="fa fa-remove"></i> 禁止登录
                </a> -->
                <a class="btn btn-info" onclick="$.table.importExcel()" shiro:hasPermission="worker:worker:import">
                    <i class="fa fa-upload"></i> 导入
                </a>
                <a class="btn btn-warning" onclick="$.table.exportExcel()" shiro:hasPermission="worker:worker:export">
                    <i class="fa fa-download"></i> 导出
                </a>
            </div>

            <div class="col-sm-12 select-table table-striped">
                <table id="bootstrap-table"></table>
            </div>
        </div>
    </div>
</div>

<th:block th:include="include :: footer" />
<th:block th:include="include :: layout-latest-js" />
<th:block th:include="include :: ztree-js" />
<script th:inline="javascript">
    var editFlag = [[${@permission.hasPermi('worker:worker:edit')}]];
    var removeFlag = [[${@permission.hasPermi('worker:worker:remove')}]];
    var resetPwdFlag = [[${@permission.hasPermi('worker:worker:resetPwd')}]];
    var prefix = ctx + "worker";

    $(function() {
        var panehHidden = false;
        if ($(this).width() < 769) {
            panehHidden = true;
        }
        $('body').layout({ initClosed: panehHidden, west__size: 185 });
        // 回到顶部绑定
        if ($.fn.toTop !== undefined) {
            var opt = {
                win:$('.ui-layout-center'),
                doc:$('.ui-layout-center')
            };
            $('#scroll-up').toTop(opt);
        }
        queryUserList();
        
        // 初始化区域下拉框
        $.ajax({
            url: ctx + "system/area/list",
            type: "post",
            data: {levelType: 1},  // 查询levelType为1的省级区域
            success: function(data) {
                console.log("区域数据:", data); // 添加日志查看返回的数据结构
                var html = '<option value="">所有省份</option>';
                // 检查data.data，因为可能返回的是AjaxResult格式
                var areaList = data.data || data;
                $.each(areaList, function(i, item) {
                    html += '<option value="' + item.areaCode + '">' + item.areaName + '</option>';
                });
                $("#provinceId").html(html);
            }
        });
        
        // 初始化技能类别下拉框
        $.ajax({
            url: ctx + "goods/category/list",
            type: "post", 
            data: {parentCategoryId: 1},  // 查询parentCategoryId为1的一级类目
            success: function(data) {
                var html = '<option value="">所有类目</option>';
                $.each(data, function(i, item) {
                    html += '<option value="' + item.goodsCategoryId + '">' + item.goodsCategoryName + '</option>';
                });
                $("#categoryLevel1").html(html);
            }
        });
    });

    function queryUserList() {
        var options = {
            url: prefix + "/list",
            removeUrl: prefix + "/remove",
            exportUrl: prefix + "/export",
            importUrl: prefix + "/importData",
            importTemplateUrl: prefix + "/importTemplate",
            sortName: "createTime",
            sortOrder: "desc",
            modalName: "师傅",
            queryParams: function(params) {
                // 先获取默认的分页参数
                var defaultParams = {
                    pageSize: params.limit,
                    pageNum: params.offset / params.limit + 1,
                    searchValue: params.search,
                    orderByColumn: params.sort,
                    isAsc: params.order
                };
                
                // 获取表单参数
                var curParams = $.common.formToJSON("user-form");
                
                // 处理区域ID，使用最后一个选中的非空区域值作为对应字段
                var streetId = $("#streetId").val();
                var districtId = $("#districtId").val();
                var cityId = $("#cityId").val();
                var provinceId = $("#provinceId").val();

                if(streetId) {
                    curParams.streetId = streetId;  // 使用streetId字段
                    curParams.areaId = districtId;  // 区县ID作为areaId
                } else if(districtId) {
                    curParams.areaId = districtId;
                } else if(cityId) {
                    curParams.areaId = cityId;
                } else if(provinceId) {
                    curParams.areaId = provinceId;
                }
                
                // 合并默认参数和自定义参数
                return $.extend(defaultParams, curParams);
            },
            columns: [{
                checkbox: true
            },
                {
                    field: 'workerId',
                    title: '师傅ID'
                },
                {
                    field: 'name',
                    title: '昵称',
                    sortable: true
                },
                {
                    field: 'phone',
                    title: '账户'
                },
                {
                    field: 'deptName',
                    title: '所属公司名称'
                },
                {
                    field: 'phone',
                    title: '手机号'
                },
                {
                    field: 'openId',
                    title: '微信唯一id',
                    visible: false
                },
                {
                    field: 'workerLogoUrl',
                    title: '头像',
                    visible: false
                },
                {
                    visible: editFlag == 'hidden' ? false : true,
                    title: '师傅状态',
                    align: 'center',
                    formatter: function (value, row, index) {
                        return statusTools(row);
                    }
                },
                {
                    visible: editFlag == 'hidden' ? false : true,
                    title: '登录状态',
                    align: 'center',
                    formatter: function (value, row, index) {
                        return loginStatusTools(row);
                    }
                },
                {
                    field: 'createTime',
                    title: '创建时间',
                    sortable: true
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function(value, row, index) {
                        if (row.workerId != 1) {
                            var actions = [];
                            actions.push('<a class="btn btn-success btn-xs " href="javascript:void(0)" onclick="areaDetail(\'' + row.workerId + '\')"><i class="fa fa-info"></i>服务区域</a> ');
                            actions.push('<a class="btn btn-success btn-xs " href="javascript:void(0)" onclick="categoryDetail(\'' + row.workerId + '\')"><i class="fa fa-info"></i>服务技能</a> ');
                            //  actions.push('<a class="btn btn-danger btn-xs ' + removeFlag + '" href="javascript:void(0)" onclick="$.operate.remove(\'' + row.workerId + '\')><i class="fa fa-remove"></i>禁止登录</a> ');
                            return actions.join('');
                        } else {
                            return "";
                        }
                    }
                }]
        };
        $.table.init(options);
    }


    /* 用户管理-重置密码 */
    function resetPwd(workerId) {
        var url = prefix + '/resetPwd/' + workerId;
        $.modal.open("重置密码", url, '800', '300');
    }

    function areaDetail(id) {
        var url = "worker/area?workerId=" + id;
        $.modal.open("区域信息", url);
    }

    function categoryDetail(id) {
        var url = "worker/goods/category?workerId=" + id;
        $.modal.open("技能信息", url);
    }

    /* 用户状态显示 */
    function statusTools(row) {
        if (row.status == 0) {
            return '<i class="fa fa-toggle-on text-info fa-2x" onclick="disable(\'' + row.workerId + '\')" title="点击停用"></i> ';
        } else {
            return '<i class="fa fa-toggle-off text-info fa-2x" onclick="enable(\'' + row.workerId + '\')" title="点击启用"></i> ';
        }
    }

    /* 用户管理-停用 */
    function disable(workerId) {
        $.modal.confirm("确认要停用用户吗？", function() {
            $.operate.post(prefix + "/changeStatus", { "workerId": workerId, "status": 1 });
        })
    }

    /* 用户管理启用 */
    function enable(workerId) {
        $.modal.confirm("确认要启用用户吗？", function() {
            $.operate.post(prefix + "/changeStatus", { "workerId": workerId, "status": 0 });
        })
    }

    /* 登录状态显示 */
    function loginStatusTools(row) {
        if (row.loginStatus == null || row.loginStatus == 0) {
            return '<i class="fa fa-toggle-on text-success fa-2x" onclick="disableLogin(\'' + row.workerId + '\')" title="点击禁用登录"></i> ';
        } else {
            return '<i class="fa fa-toggle-off text-danger fa-2x" onclick="enableLogin(\'' + row.workerId + '\')" title="点击启用登录"></i> ';
        }
    }

    /* 禁用登录 */
    function disableLogin(workerId) {
        $.modal.confirm("确认要禁用该师傅的登录权限吗？", function() {
            $.operate.post(prefix + "/changeLoginStatus", { "workerId": workerId, "loginStatus": 1 });
        })
    }

    /* 启用登录 */
    function enableLogin(workerId) {
        $.modal.confirm("确认要启用该师傅的登录权限吗？", function() {
            $.operate.post(prefix + "/changeLoginStatus", { "workerId": workerId, "loginStatus": 0 });
        })
    }

    // 区域联动处理
    function areaChange(obj, nextId) {
        var parentCode = $(obj).val();
        if (parentCode) {
            $.ajax({
                url: ctx + "system/area/list",
                type: "post",
                data: {parentCode: parentCode},
                success: function(data) {
                    console.log("下级区域数据:", data);
                    var html = '<option value="">' + getAreaLevelName(nextId) + '</option>';
                    var areaList = data.data || data;
                    $.each(areaList, function(i, item) {
                        html += '<option value="' + item.areaCode + '">' + item.areaName + '</option>';
                    });
                    $("#" + nextId).html(html);
                    // 清空下级选项
                    clearLowerLevels(nextId);
                }
            });
        } else {
            $("#" + nextId).html('<option value="">' + getAreaLevelName(nextId) + '</option>');
            // 清空下级选项
            clearLowerLevels(nextId);
        }
    }

    // 获取区域层级名称
    function getAreaLevelName(levelId) {
        switch(levelId) {
            case 'cityId':
                return '所有城市';
            case 'districtId':
                return '所有区县';
            case 'streetId':
                return '所有街道';
            default:
                return '所有';
        }
    }

    // 清空下级选项
    function clearLowerLevels(currentId) {
        var levels = ['cityId', 'districtId', 'streetId'];
        var startClearing = false;
        
        for(var i = 0; i < levels.length; i++) {
            if(startClearing) {
                $("#" + levels[i]).html('<option value="">' + getAreaLevelName(levels[i]) + '</option>');
            }
            if(levels[i] === currentId) {
                startClearing = true;
            }
        }
    }

    // 类目联动处理
    function categoryChange(obj, nextId) {
        var parentId = $(obj).val();
        if (parentId) {
            $.ajax({
                url: ctx + "goods/category/list",
                type: "post",
                data: {parentCategoryId: parentId},  // 直接使用选中的ID作为父类目ID查询
                success: function(data) {
                    var html = '<option value="">' + (nextId === 'categoryLevel2' ? '所有二级类目' : '所有三级类目') + '</option>';
                    $.each(data, function(i, item) {
                        html += '<option value="' + item.goodsCategoryId + '">' + item.goodsCategoryName + '</option>';
                    });
                    $("#" + nextId).html(html);
                    // 清空下级选项
                    if(nextId === 'categoryLevel2') {
                        $("#categoryLevel3").html('<option value="">所有三级类目</option>');
                    }
                }
            });
        } else {
            $("#" + nextId).html('<option value="">' + (nextId === 'categoryLevel2' ? '所有二级类目' : '所有三级类目') + '</option>');
            if(nextId === 'categoryLevel2') {
                $("#categoryLevel3").html('<option value="">所有三级类目</option>');
            }
        }
    }

    // 修改重置函数，确保重置时清空所有区域选择
    $.form.reset = function() {
        var currentForm = document.getElementById("user-form");
        currentForm.reset();
        // 手动清空所有区域下拉框
        $("#provinceId").html('<option value="">所有省份</option>');
        $("#cityId").html('<option value="">所有城市</option>');
        $("#districtId").html('<option value="">所有区县</option>');
        $("#streetId").html('<option value="">所有街道</option>');
        // 手动清空所有类目下拉框
        $("#categoryLevel2").html('<option value="">二级类目</option>');
        $("#categoryLevel3").html('<option value="">三级类目</option>');
        // 重新加载一级数据
        loadInitialData();
        $.table.search();
    }

    // 添加初始数据加载函数
    function loadInitialData() {
        // 加载省份数据
        $.ajax({
            url: ctx + "system/area/list",
            type: "post",
            data: {levelType: 1},
            success: function(data) {
                var html = '<option value="">所有省份</option>';
                var areaList = data.data || data;
                $.each(areaList, function(i, item) {
                    html += '<option value="' + item.areaCode + '">' + item.areaName + '</option>';
                });
                $("#provinceId").html(html);
            }
        });

        // 加载一级类目
        $.ajax({
            url: ctx + "goods/category/list",
            type: "post",
            data: {parentCategoryId: 1},
            success: function(data) {
                var html = '<option value="">所有类目</option>';
                $.each(data, function(i, item) {
                    html += '<option value="' + item.goodsCategoryId + '">' + item.goodsCategoryName + '</option>';
                });
                $("#categoryLevel1").html(html);
            }
        });
    }
</script>
</body>
<!-- 导入区域 -->
<script id="importTpl" type="text/template">
    <form enctype="multipart/form-data" class="mt20 mb10">
        <div class="col-xs-offset-1">
            <input type="file" id="file" name="file"/>
            <div class="mt10 pt5">
                <input type="checkbox" id="updateSupport" name="updateSupport" title="如果登录账户已经存在，更新这条数据。"> 是否更新已经存在的用户数据
                &nbsp;	<a onclick="$.table.importTemplate()" class="btn btn-default btn-xs"><i class="fa fa-file-excel-o"></i> 下载模板</a>
            </div>
            <font color="red" class="pull-left mt10">
                提示：仅允许导入"xls"或"xlsx"格式文件！
            </font>
        </div>
    </form>
</script>
</html>