<template>
    <div class="flex-container">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
            <!-- 搜索区域 -->
            <a-form layout="inline">
                <a-row :gutter="24">
                    <a-col :md="3" :sm="6">
                        <a-form-item label="账号">
                            <a-input placeholder="账号" v-model="queryParam.account"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :md="3" :sm="6">
                        <a-form-item  label="姓名">
                            <a-input  placeholder="姓名" v-model="queryParam.name"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :md="3" :sm="6">
                        <a-form-item label="县分">
                            <a-select v-model="queryParam.substName" @change="getSchoolNames">
                                <a-select-option key="">--全部--</a-select-option>
                                <a-select-option v-for="d in subNames" :key="d.value" :value="d.value">{{d.text}}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="5" :sm="10">
                        <a-form-item label="学校">
                            <a-select v-model="queryParam.schoolName">
                                <a-select-option key="">--全部--</a-select-option>
                                <a-select-option v-for="d in schoolNames" :key="d.value" :value="d.value">{{d.text}}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <span class="table-page-search-submitButtons" style="float: left; overflow: hidden;">
                        <a-col :md="6" :sm="24">
                            <a-button @click="search()" type="primary">查询</a-button>
                            <a-button @click="openAllocation()" style="margin-left: 8px" icon="plus" type="primary">新增</a-button>
                        </a-col>
                    </span>
                </a-row>
            </a-form>

            <!--列表-->
            <s-table :columns="columns" :data="rowdata" bordered ref="table" size="small" class="flex-filling"  :locale="emptyText">
                <template slot="operation" slot-scope="text, record">
                    <a-divider type="vertical"/>
                        <a-popconfirm title="是否要删除此行？" @confirm="deleteAllocation(record.id)">
                            <a>删除</a>
                        </a-popconfirm>
                    <a-divider type="vertical"/>
                </template>
            </s-table>

            <!--编辑----弹框-->
            <a-modal :title="titleName" :visible="modifyvisible"  @ok="createfunctionOk" @cancel="createfunctionCancel" html-type="submit" width="720px" height="1600px">
                <a-form :form="Formtable">
                    <a-form-item :labelCol="{span: 6}"  :wrapperCol="{span: 8, offset: 1}"  label="账号">
                        <template v-for="(tag, index) in modifyForm.userName">
                            <a-tooltip v-if="tag.length > 20" :key="tag" :title="tag">
                                <a-tag :key="tag" :closable="index !== 0" @close="() => handleClose(tag)">
                                    {{ `${tag.slice(0, 20)}...` }}
                                </a-tag>
                            </a-tooltip>
                            <a-tag v-else :key="tag" :closable="index !== 0" @close="() => handleClose(tag)">
                                {{ tag }}
                            </a-tag>
                        </template>
                        <a-input
                            v-if="inputVisible"
                            ref="input"
                            type="text"
                            size="small"
                            :style="{ width: '78px' }"
                            :value="inputValue"
                            @change="handleInputChange"
                            @blur="handleInputConfirm"
                            @keyup.enter="handleInputConfirm"
                        />
                        <a-tag v-else style="background: #fff; borderStyle: dashed;" @click="showInput">
                            <a-icon type="plus" /> 添加账号
                        </a-tag>
                    </a-form-item>
                    <a-form-item :labelCol="{span: 6}"  :wrapperCol="{span: 8, offset: 1}"  label="县分">
                        <a-select placeholder="请选择" @change="getSchoolNames2" v-model="modifyForm.subName" >
                            <a-select-option key="">请选择</a-select-option>
                            <a-select-option v-for="d in subNames2" :value="d.value">{{ d.text}}</a-select-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item :labelCol="{span: 6}" :wrapperCol="{span: 8, offset: 1}"  label="学校名称">
                        <a-select placeholder="请选择" v-model="modifyForm.schoolId">
                            <a-select-option key="">请选择</a-select-option>
                            <a-select-option v-for="d in schoolNames2"  :value="d.id">{{ d.schoolName}}</a-select-option>
                        </a-select>
                    </a-form-item>

                </a-form>
            </a-modal>
        </div>
    </div>
</template>

<script>
    import STable from '@/components/table';
    import {getList,addAllocation,deleteAllocation} from "../../../api/school-center/schoolAllocationAPI"
    import {cloneObject} from '@/utils/util'
    import treecheck from '@/components/sysmanage/treeCheck'
    import treeList from '@/components/sysmanage/treeList'
    import {getSchoolNames, initSubstName, initUsers} from "../../../api/school-center/userManager/newUserAPI";

    export default {
        name: "schoolAllocation",
        components: {
            STable,
            treeList,
            treecheck,
        },
        data: function () {
            return {
                inputVisible: false,
                inputValue: '',
                emptyText: {emptyText: '暂无数据'},
                Formtable: this.$form.createForm(this, {name: 'Formtable'}),
                queryParam: {
                    account: '',
                    name: '',
                    substName:'',
                    schoolName: '',
                },
                titleName: '',
                modifyvisible:false,
                subNames: [],
                schoolNames: [],
                userList:[],
                subNames2: [],
                schoolNames2: [],
                modifyForm: {
                    id: '',
                    userName: [],
                    subName: '',
                    account: '',
                    schoolId: '',
                },
                autoCompleteResult:[],
                schoolList:[],
                addSubName:'',
                columns: [
                    {dataIndex: 'name', width: 100, title: '姓名 ', align: "center"},
                    {dataIndex: 'account', width: 100, title: '账号', align: "center"},
                    {dataIndex: 'substName', width: 100, title: '管辖学校所属县分 ', align: "center"},
                    {dataIndex: 'schoolName', width: 200, title: '管辖学校 ', align: "center"},
                    {
                        dataIndex: 'operation',
                        width: 100,
                        title: '操作',
                        align: "center",
                        scopedSlots: {customRender: 'operation'},
                        fixed: "right"
                    }]
                ,
                rowdata: parameter => {
                    let params = {
                        pageNo: parameter.pageNo,
                        pageSize: parameter.pageSize
                    }

                    //表示
                    let obj = cloneObject(this.queryParam)
                    return getList(Object.assign(params,obj)).then(res => {
                        let data = {}
                        if (res.state !== 'success') {
                            this.$message.error("查询失败！", 5);
                            this.emptyText.emptyText = '查询失败！'
                            data = {
                                data: [],
                                pageSize: parameter.pageSize,
                                pageNo: 1,
                                totalCount: 0
                            }
                        } else {
                            data = {
                                data: res.data.records,
                                pageSize: parameter.pageSize,
                                pageNo: parameter.pageNo,
                                totalCount: res.data.total
                            }
                        }
                        return data
                    })
                },
                keyRecord: '',
                recordId: '',
                addUser: false,
            }
        },
        methods:{
            search() {
                this.$refs.table.refresh({search: true})
            },
            openAllocation() {
                this.titleName = "添加学校分配";
                this.modifyvisible = true;
            },
            handleChange(value) {
                console.log(`selected ${value}`);
            },
            //提交表单
            createfunctionOk(){
                this.Formtable.validateFields(["account"], {force: true}, (err, values)=>{
                    if (!err){
                        for (const userName of this.modifyForm.userName) {
                            this.modifyForm.account = userName +",";
                        }
                        addAllocation({"account":this.modifyForm.account,"schoolId":this.modifyForm.schoolId}).then(res=>{
                            if (res.state=="success") {
                                this.$message.success(res.data ? res.data : '添加成功！', 5);
                                this.modifyForm.account = ""
                                this.modifyvisible = false;
                                this.search();
                            }
                            this.$message.error(res.data ? res.data : '添加失败！', 5);
                        })
                    }
                })
            },
            createfunctionCancel(){
                this.modifyvisible=false
                this.autoCompleteResult=[]
                this.Formtable.setFieldsValue({
                    account: ''
                })

            },
            deleteAllocation(id){
                let params = {};
                params.id = id;
                deleteAllocation(params).then(res=>{
                    if (res.state=="success") {
                        this.$message.success(res.data ? res.data : '删除成功！', 5);
                        this.search();
                        this.modifyvisible = false;
                    }else{

                        this.$message.error(res.data ? res.data : '删除失败！', 5);
                    }
                })
            },
            getSchoolNames() {
                this.schoolNames = []
                this.queryParam.schoolName = ''
                getSchoolNames({"substName": this.queryParam.substName}).then((res) => {
                    if (res.state == "success") {
                        const result = res.data
                        result.forEach((r) => {
                            if (r.schoolName === 'null')
                                return;
                            this.schoolNames.push({
                                value: r.schoolName,
                                text: r.schoolName
                            })
                        })
                    }
                })
            },
            initSubstName() {
                initSubstName().then((res) => {
                    if (res.state == "success") {
                        const result = res.data
                        result.forEach((r) => {
                            if (r.subName === 'null')
                                return;
                            this.subNames.push({
                                value: r.subName,
                                text: r.subName
                            })
                        })
                    }
                })
            },
            handleClose(removedTag) {
                const tags = this.modifyForm.userName.filter(tag => tag !== removedTag);
                console.log(tags);
                this.modifyForm.userName = tags;
            },

            showInput() {
                this.inputVisible = true;
                this.$nextTick(function() {
                  this.$refs.input.focus();
                });
            },

            handleInputChange(e) {
                this.inputValue = e.target.value;
            },

            handleInputConfirm() {
                const inputValue = this.inputValue;
                let tags = this.modifyForm.userName;
                if (inputValue && tags.indexOf(inputValue) === -1) {
                    tags = [...tags, inputValue];
                }
                console.log(tags);
                this.modifyForm.userName = tags;
                this.inputVisible = false;
                this.inputValue = '';

            },
            getSchoolNames2() {
                this.schoolNames2 = []
                this.modifyForm.schoolId = ''
                getSchoolNames({"substName": this.modifyForm.subName}).then((res) => {
                    if (res.state == "success") {
                        const result = res.data
                        result.forEach((r) => {
                            if (r.schoolName === 'null')
                                return;
                            this.schoolNames2.push({
                                id: r.id,
                                schoolName: r.schoolName
                            })
                        })
                    }
                })
            },
            initSubstName2() {
                initSubstName().then((res) => {
                    if (res.state == "success") {
                        const result = res.data
                        result.forEach((r) => {
                            if (r.subName === 'null')
                                return;
                            this.subNames2.push({
                                value: r.subName,
                                text: r.subName
                            })
                        })
                    }
                })
            },
            initUsers(){
                initUsers().then((res) => {
                    if (res.state == "success") {
                        const result = res.data
                        result.forEach((r) => {
                            if (r.name === 'null')
                                return;
                            this.userList.push({
                                account: r.account,
                                text: r.name,
                                value: r.name,
                            })
                        })
                    }
                })
            }
        },
        mounted() {
            this.initUsers();
            this.initSubstName();
            this.getSchoolNames();
            this.initSubstName2();
            this.getSchoolNames2();
        }
    }
</script>

<style scoped>

</style>