<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="销售" prop="companyUserId">
                <el-select
                    v-model="queryParams.companyUserId"
                    placeholder="请输入销售id或名称筛选，默认100条"
                    clearable
                    filterable
                    remote
                    :remote-method="(keyword) => companyUserRemoteSearch(keyword, queryParams.companyUserId)"
                    style="width: 290px;"
                >
                    <el-option
                        v-for="item in companyUserOptions"
                        :key="item.dictValue"
                        :label="`${item.dictLabel}(${item.dictValue})`"
                        :value="item.dictValue"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="部门" prop="deptId">
                <treeselect
                    v-model="queryParams.deptId"
                    :options="deptOptions"
                    :normalizer="normalizer"
                    placeholder="选择部门"
                    style="width: 220px"
                />
            </el-form-item>
            <el-form-item label="含子部门" prop="includeChild">
                <el-switch v-model="queryParams.includeChild"/>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    v-hasPermi="['app:comuserdept:add']"
                    @click="handleAdd"
                >
                    新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="danger"
                    plain
                    icon="el-icon-delete"
                    size="mini"
                    :disabled="ids.length === 0"
                    v-hasPermi="['app:comuserdept:delete']"
                    @click="handleDelete"
                >
                    删除
                </el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="customerBindList" @selection-change="handleSelectionChange" border>
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="销售ID" align="center" prop="companyUserId" min-width="100"/>
            <el-table-column label="销售名称" align="center" prop="companyUserName" min-width="150"/>
            <el-table-column label="销售账号" align="center" prop="companyUserAccount" min-width="150"/>
            <el-table-column label="部门" align="center" prop="deptName" min-width="120"/>
            <el-table-column label="创建时间" align="center" prop="createTime" min-width="120"/>
            <el-table-column label="修改时间" align="center" prop="updateTime" min-width="120"/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" min-width="120">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        v-hasPermi="['app:comuserdept:edit']"
                        @click="handleUpdate(scope.row)"
                    >修改</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改客服绑定关系 -->
        <el-dialog
            :title="bindDialog.title"
            :visible.sync="bindDialog.visible"
            width="500px"
            append-to-body
            :close-on-click-modal="false"
        >
            <el-form ref="bindForm" :model="bindForm" :rules="rules" label-width="80px">
                <el-form-item label="销售" prop="companyUserId">
                    <el-select
                        v-model="bindForm.companyUserId"
                        placeholder="请输入销售id或名称筛选，默认100条"
                        clearable
                        filterable
                        remote
                        style="width: 290px;"
                        :remote-method="(keyword) => companyUserRemoteSearch(keyword, bindForm.companyUserId)"
                    >
                        <el-option
                            v-for="item in companyUserOptions"
                            :key="item.dictValue"
                            :label="`${item.dictLabel}(${item.dictValue})`"
                            :value="item.dictValue"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="部门" prop="deptId">
                    <treeselect
                        v-model="bindForm.deptId"
                        :options="deptOptions"
                        :normalizer="normalizer"
                        placeholder="选择部门"
                        style="width: 290px;"
                    />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { findList, getById, deleteByIds, add, edit, findCompanyUserOptions, } from "@/api/app/customerBind";
import { listDept } from '@/api/system/appDept';
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
    name: "CustomerBind",
    components: { Treeselect },
    data() {
        return {
            // 部门树形选择器选项
            deptOptions: [],
            companyUserOptions: [],
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 客服/销售绑定部门表格数据
            customerBindList: [],
            bindDialog: {
                visible: false,
                loading: false,
                title: null,
            },
            // 表单参数
            bindForm: {
                id: null,
                companyUserId: null,
                deptId: null
            },
            // 表单校验
            rules: {
                companyUserId: [
                    { required: true, message: "销售不可为空", trigger: "blur" },
                ],
                deptId: [
                    { required: true, message: "部门不可为空", trigger: "blur" },
                ],
            },
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                companyUserId: null,
                deptId: null,
                includeChild: false,
            },
        };
    },
    created() {
        this.getList();
        this.getDeptList();
        this.getCompanyUserOptions(null);
    },
    methods: {
        /** 列表查询 */
        getList() {
            this.loading = true;
            findList(this.queryParams).then(response => {
                this.customerBindList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        /**
         * 获取部门树形数据
         */
        getDeptList() {
            listDept().then(response => {
                if (response.code === 200) {
                    // 转换为树形结构
                    this.deptOptions = this.handleTree(response.data, "deptId");
                } else {
                    this.deptOptions = [];
                }
            }).catch(() => {
                this.deptOptions = [];
            });
        },
        /**
         * 获取销售列表
         */
        async getCompanyUserOptions(keyword, selectedId) {
            let res = await findCompanyUserOptions({keyword: keyword, selectedId: selectedId, pageNumber: 1, pageSize: 100});
            this.companyUserOptions = res.data;
        },
        companyUserRemoteSearch(keyword, selectedId) {
            this.getCompanyUserOptions(keyword, selectedId);
        },
        /**
         * 树形结构转换
         */
        handleTree(data, id, parentId, children) {
            id = id || 'id';
            parentId = parentId || 'parentId';
            children = children || 'children';
            var tree = [];
            var map = {};
            data.forEach(function(item) {
                map[item[id]] = item;
            });
            data.forEach(function(item) {
                var parent = map[item[parentId]];
                if (parent) {
                    (parent[children] || (parent[children] = [])).push(item);
                } else {
                    tree.push(item);
                }
            });
            return tree;
        },
         /**
         * 树形选择器数据格式化
         */
        normalizer(node) {
            if (node.children && !node.children.length) {
                delete node.children;
            }
            return {
                id: node.deptId,
                label: node.deptName,
                children: node.children
            };
        },
        // 取消按钮
        cancel() {
            this.bindDialog.visible = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.bindForm = {
                id: null,
                companyUserId: null,
                deptId: null,
            };
            this.resetForm("bindForm");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.queryParams = {
                pageNum: 1,
                pageSize: 10,
                companyUserId: null,
                deptId: null,
                includeChild: false,
            };
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id);
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.bindDialog.title = "添加绑定关系";
            this.bindDialog.visible = true;
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            getById(row.id ).then(response => {
                for (let key in this.bindForm) {
                    this.bindForm[key] = response.data[key] || null;
                }
                this.bindDialog.title = "修改绑定关系";
                this.bindDialog.visible = true;
            });
        },
        handleDelete() {
            this.$confirm('是否确认删除?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(async () => {
                await deleteByIds(this.ids);
                this.getList();
                this.msgSuccess("删除成功");
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["bindForm"].validate(valid => {
                if (valid) {
                    if (this.bindForm.id != null) {
                        edit(this.bindForm).then(response => {
                            this.msgSuccess("修改成功");
                            this.bindDialog.visible = false;
                            this.getList();
                        });
                    } else {
                        add(this.bindForm).then(response => {
                            this.msgSuccess("新增成功");
                            this.bindDialog.visible = false;
                            this.getList();
                        });
                    }
                }
            });
        },
    }
};
</script>
