<template>
    <div class="random">
        <el-row>
            <el-col :span="12">
                <el-button type="primary" @click="$router.back()">上级</el-button>
                <el-button type="success" @click="showAdd">新增</el-button>
            </el-col>
            <el-col :span="12" style="text-align: right;">
                <el-input v-model="search_tagname" style="width: 200px; margin-right: 5px;" placeholder="请输入标签名称"></el-input>
                <el-button icon="el-icon-search" @click="loadData()">搜索</el-button>
            </el-col>
        </el-row>
        <div class="custom-table">
            <el-table
                :data="tableData"
                border
                style="width: 100%"
                v-loading="loading">
                <el-table-column type="index" align="center" label="序号" width="80"/>
                <el-table-column prop="tag_name" show-overflow-tooltip label="标签名称">
                    <template slot-scope="scope">{{ scope.row.tag_name }}</template>
                </el-table-column>
                <el-table-column prop="tag_name" show-overflow-tooltip label="对应单位数">
                    <template slot-scope="scope">{{ enforce_obj_count[scope.row.id + ''] ? enforce_obj_count[scope.row.id + ''] : 0 }}</template>
                </el-table-column>
                <el-table-column prop="action" label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button type="primary" @click="showUpdate(scope.row.id, scope.row.tag_name)">修改</el-button>
                        <el-button type="danger" @click="deleteTag(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="custom-pagination">
                        <div class="info">
                            <span>共 {{ total }} 条记录</span>
                            <span>第 {{ query.page }} / {{ pageTotal }} 页</span>
                        </div>
                        <el-pagination
                            background
                            class="custom-page"
                            layout="prev, pager, next, sizes"
                            :page-sizes="[5,10, 20, 50, 100]"
                            :current-page="query.page"
                            :page-size="query.size"
                            :total="total"
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange">
                        </el-pagination>
                    </div>
        </div>
        <el-dialog :visible.sync="addFlag" v-if="addFlag" :title="'新增'">
            <el-form :model="tagForm" ref="tagForm" label-width="100px" :rules="rules" class="custom-form">
                <el-form-item label="标签名称" prop="tag_name">
                    <el-input v-model="tagForm.tag_name" maxlength="50" placeholder="请输入标签名称"></el-input>
                </el-form-item>
                <el-row style="text-align: center;">
                    <el-button @click="addFlag = false">取消</el-button>
                    <el-button type="primary" @click="saveData()">确定</el-button>
                </el-row>
            </el-form>
        </el-dialog>
        <el-dialog :visible.sync="updateFlag" v-if="updateFlag" :title="'修改'">
            <el-form :model="tagUpdateForm" ref="tagUpdateForm" label-width="100px" :rules="rules" class="custom-form">
                <el-form-item label="标签名称" prop="tag_name">
                    <el-input v-model="tagUpdateForm.tag_name" maxlength="50" placeholder="请输入标签名称"></el-input>
                </el-form-item>
                <el-row style="text-align: center;">
                    <el-button @click="updateFlag = false">取消</el-button>
                    <el-button type="primary" @click="updateData()">确定</el-button>
                </el-row>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>

import {getTags, addTag, deleteTag, updateTag, statTag, statBatchTag} from "@/api/random"
import {removeOneJob} from "@/api/job";

export default {
    computed: {
        pageTotal() {
            const page = Math.ceil(this.total / this.query.size)
            return page > 0 ? page : 1
        }
    },
    components: {},
    data() {
        return {
            search_tagname:'',
            id: '',
            subId: 0,
            tagForm: {
                tag_name: '',
            },
            tagUpdateForm: {
                tag_name: '',
            },
            enforce_obj_count: {},
            addFlag: false,
            updateFlag: false,
            loading: false,
            rules: {
                tag_name: [
                    {required: true, message: '请输入标签名称', trigger: 'blur'}
                ]
            },
            tableData: [],
            query: {
                page: 1,
                size: 10
            },
            total: 0,
        }
    },
    mounted() {
        let id = this.$route.query.id
        this.id = id
        this.loadData()
    },
    methods: {
        loadData() {
            this.loading = true
            let expressions = []
            if (this.search_tagname) {
                expressions.push("tag_name" + "==" + "'" + this.search_tagname + "'")
            }
            this.query.query = 'parent_id==' + this.id
            this.query.query += ';level==2'
            if (this.search_tagname) {
                this.query.query = this.query.query + ";tag_name=='*"+this.search_tagname + "*'"
            }

            getTags(this.query).then(res => {
                // if (res && res.data) {
                //   let tags = res.data || []
                //   this.total = res.total
                //
                //   this.tableData = tags
                //   let tagIds = tags.map(item => item.id)
                //   for (let index in tags) {
                //     if (tags[index].sub_tags && tags[index].sub_tags.length > 0) {
                //       let subTagIds = tags[index].sub_tags.map(item => item.id)
                //       tagIds = tagIds.concat(subTagIds)
                //     }
                //   }
                //   statBatchTag({ids: tagIds.join(',')}).then(res => {
                //     this.enforce_obj_count = JSON.parse(res.statics)
                //   })
                // }
                // this.loading = false

                if (res) {
                  this.tableData = res.data || []
                  this.total = res.total
                  let enforce_obj_count = {}
                  let tasks = []
                  for (let index in this.tableData) {
                    tasks.push(new Promise((resolve, reject) => {
                      statTag(this.tableData[index].id, {}).then(res => {
                        console.log(this.tableData[index].id, res)
                        enforce_obj_count[this.tableData[index].id + ''] = res.total
                        resolve(res)
                      })
                    }))
                  }
                  Promise.all(tasks).then(res => {
                    this.enforce_obj_count = enforce_obj_count
                  })
                }
                this.loading = false
            })
        },
        showAdd() {
            this.tagForm.tag_name = ''
            this.addFlag = true
        },
        showUpdate(subId, name) {
            this.subId = subId
            this.tagUpdateForm.tag_name = name
            this.updateFlag = true
        },
        saveData() {
            let data = {
                parent_id: parseInt(this.id),
                tag_name: this.tagForm.tag_name,
                level: 2,
                sort: 1
            }
            addTag(data).then(res => {
                this.$message.success("添加成功")
                this.addFlag = false
                this.tag_name = ''
                this.loadData(this.id,1)
            })
        },
        updateData() {
            let data = {
                id: parseInt(this.subId),
                parent_id: parseInt(this.id),
                tag_name: this.tagUpdateForm.tag_name,
                level: 2,
                sort: 1
            }
            updateTag(this.subId, data).then(res => {
                this.$message.success("修改成功")
                this.updateFlag = false
                this.tag_name = ''
                this.loadData(this.id,1)
            })
        },
        deleteTag(subId) {
            this.$confirm('删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteTag(subId).then(res => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.restForm = !this.restForm
                    this.loadData(this.id,1)
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '取消删除'
                });
            });
        },

        handleSizeChange(val) {
            this.query.size = val
            this.loadData()
        },
        handleCurrentChange(val) {
            this.query.page = val
            this.loadData()
        }
    }
}
</script>
