<template>
    <div>
        <div class="top-box flex-align">
            <div>
                <a-button type="primary" style="margin-right: 24px;" @click="showModal('add')">创建知识点</a-button>
                <!-- <a-button type="primary" style="margin-right: 24px;">导入知识点</a-button>
                <a-button type="primary">删除</a-button> -->
            </div>
            <div class="flex">
                <a-select :default-value="receiveData.id" placeholder="请选择学科" style="width:300px;margin-right: 8px;"
                    @change="subjectChange">
                    <a-select-option :value="''">
                        全部
                    </a-select-option>
                    <a-select-opt-group v-for="(val,key) in $store.state.baseInfo.SubjectsGroup" :key="key">
                        <span slot="label">{{key}}</span>
                        <a-select-option :value="v.id" v-for="v in val" :key="v.id">
                            {{v.name}}
                        </a-select-option>
                    </a-select-opt-group>
                </a-select>
                <a-input-search style="width:400px;" placeholder="搜索知识点" enter-button @search="onSearch" />
            </div>
        </div>
        <a-table @expand="myExpand" :columns="columns" :loading="loading" :dataSource="data" size="small"
            :rowKey="record => record.id" :pagination="pagination" @change="handleChange">
            <template slot="action" slot-scope="text,record">
                <a @click="showModal('edit',record)">修改</a>
                <a-divider type="vertical" />
                <a @click="_KnowledgePointGetDelete(record)">删除</a>
                <a-divider type="vertical" />
                <a @click="showModal('addChild',record)">添加子知识点</a>
            </template>
        </a-table>
        <EditKnowledgePoints ref="EditKnowledgePoints" />
    </div>
</template>
<script>
    const columns = [
        {
            title: "知识点名称",
            dataIndex: "name",
            key: "name",
            scopedSlots: { customRender: "name" },
            ellipsis: true,
            width: 180
        },
        {
            title: "所属学科",
            dataIndex: "discipline",
            key: "discipline",
            scopedSlots: { customRender: "discipline" },
            ellipsis: true,
            width: 100
        },
        {
            title: "操作",
            key: "action",
            dataIndex: "action",
            scopedSlots: { customRender: "action" },
            width: 100,
            align: "center"
        },
    ]
    import { myPagination } from '@/mixins/myPagination.js'
    import EditKnowledgePoints from './EditKnowledgePoints.vue'
    import { KnowledgePointGetList, KnowledgePointGetDelete } from '@/api/api'
    import { searchOption } from '@/utils/tools'
    export default {
        props: {
            receiveData: {
                type: Object,
                default: () => { }
            }
        },
        mixins: [myPagination],
        components: {
            EditKnowledgePoints
        },
        data() {
            return {
                columns,
                loading: false,
                data: [],
                selectedRowKeys: [],
                selectedRows: [],
                DisciplineId: this.receiveData.id,//学科id
            }
        },
        mounted() {
            this.$store.dispatch('DisciplineGetList');
            this.$store.dispatch('GetQuestionTypeList');
            this._KnowledgePointGetList();
        },
        methods: {
            subjectChange(value) {
                console.log(value)
                this.DisciplineId = value;
                this._KnowledgePointGetList();
            },
            //删除知识点
            _KnowledgePointGetDelete(record) {
                let _this = this;
                this.$confirm({
                    okText: '确认',
                    cancelText: '取消',
                    mask: false,
                    title: `您确认要删除"${record.name}"知识点吗?`,
                    onOk() {
                        _this.loading = true;
                        let data = {
                            id: record.id
                        }
                        KnowledgePointGetDelete(data).then(res => {
                            _this.$message.success('删除成功！');
                            // _this._KnowledgePointGetList();
                            searchOption(record, _this.data);
                            _this.loading = false;
                        }).catch(err => {
                            _this.loading = false;
                        })
                    }
                });
            },
            //知识点列表
            _KnowledgePointGetList(obj = {}) {
                this.loading = true;
                let data = {
                    ParentId: '',//父级知识点id
                    DisciplineId: this.DisciplineId,//所属学科id
                    CognitiveAbilityId: '',//只是能力id
                    KeyWord: this.KeyWord,
                    SkipCount: (this.pagination.current - 1) * this.pagination.pageSize,
                    MaxResultCount: this.pagination.pageSize,
                    ...obj
                }
                KnowledgePointGetList(data).then(res => {
                    console.log(res, '知识点列表')
                    this.data = res.items.map(item => {
                        if (item.hasChild) {
                            item.children = []
                        }
                        return item
                    });
                    this.pagination.total = res.totalCount;
                    this.loading = false;
                }).catch(err => {
                    this.loading = false;
                })
            },
            showModal(type, record = {}) {
                if (type === 'add' && this.selectedRows.length > 1) {
                    this.$message.error('只能选择一个父级知识点进行创建！')
                    return;
                }
                let parentData = this.selectedRows.length > 0 ? this.selectedRows[0] : {}
                this.$refs.EditKnowledgePoints.showModal(type, record, parentData);
            },
            onSearch(val) {
                this.KeyWord = val;
                const pager = { ...this.pagination };
                pager.current = 1;
                this.pagination = pager;
                this._KnowledgePointGetList();
            },
            //表格选项选中
            onSelectChange(selectedRowKeys, selectedRows) {
                console.log(selectedRowKeys, 'selectedRowKeys')
                console.log(selectedRows, 'selectedRows')
                this.selectedRowKeys = selectedRowKeys;
                this.selectedRows = selectedRows;
            },
            //表格change
            handleChange(pagination, filters, sorter) {
                const pager = { ...this.pagination };
                pager.current = pagination.current;
                this.pagination = pager;
                this._KnowledgePointGetList();
            },
            loadChild(record, obj = {}) {
                console.log(record, 'record')
                this.loading = true;
                let data = {
                    ParentId: record.id || '',//父级知识点id
                    DisciplineId: this.DisciplineId,//所属学科id
                    CognitiveAbilityId: '',//只是能力id
                    KeyWord: '',
                    SkipCount: 0,
                    MaxResultCount: 99999,
                    ...obj
                }
                KnowledgePointGetList(data).then(res => {
                    if (res.items.length == 0 && record.hasOwnProperty('children')) {
                        delete record.children;
                    } else {
                        record.children = res.items.map(item => {
                            if (item.hasChild) {
                                item.children = []
                            }
                            return item
                        });
                    }
                    this.loading = false;
                }).catch(err => {
                    this.loading = false;
                })
            },
            myExpand(expanded, record) {
                console.log(expanded, record)
                if (expanded && record.children.length === 0) {
                    this.loadChild(record);
                }
            },
            searchOption(option, arr, type = 'delect', obj = {}) {
                //首先循环arr最外层数据
                for (let s = 0; s < arr.length; s++) {
                    //如果匹配到了arr最外层中的我需要修改的数据
                    if (arr[s].id === option.id) {
                        //判断需要操作的类型
                        if (type === 'delect') {
                            //删除即删除即可
                            arr.splice(s, 1)
                        } else {
                            //如果是修改，利用Object.assign()组合符合arr数据格式的对象，并进行修改
                            this.$set(
                                arr,
                                s,
                                Object.assign(obj, {
                                    id: obj.pid,
                                    title: obj.menuName,
                                    children: option.children,
                                    scopedSlots: { title: 'custom' }
                                })
                            )
                        }
                        break
                    } else if (arr[s].children && arr[s].children.length > 0) {
                        // 递归条件
                        this.searchOption(option, arr[s].children, type, obj)
                    } else {
                        continue
                    }
                }
            },
        }
    }
</script>
<style scoped>
    .top-box {
        height: 64px;
        padding: 0 24px;
    }
</style>