<template>
    <div class="app-container">
        <el-form :inline="true" :model="form" size="mini">
            <el-form-item><el-button type="primary" @click="onSubmit">查询</el-button></el-form-item>
            <el-form-item><el-button @click="onReset">重置</el-button></el-form-item>
            <el-form-item><el-button type="warning" @click="onAdd">添加</el-button></el-form-item>
        </el-form>
        <el-table v-loading="isLoading" element-loading-text="Loading" :data="list" size="mini" border stripe fit highlight-current-row>
            <el-table-column prop="name" label="页面名称" align="center" width="150"></el-table-column>
            <el-table-column prop="url" label="页面路径" align="center" width="150"></el-table-column>
            <el-table-column prop="type" label="页面类型" align="center" width="150"></el-table-column>
            <el-table-column prop="desc" label="页面描述" align="center" width="200"></el-table-column>
            <el-table-column prop="create_at" label="创建时间" width="150"></el-table-column>
            <el-table-column prop="create_by.username" label="创建者" width="150"></el-table-column>
            <el-table-column prop="update_at" label="更新时间" width="150" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="update_by.username" label="更新者" width="150"></el-table-column>
            <el-table-column label="操作" align="center" min-width="180" fixed="right">
                <template slot-scope="scope">
                    <el-button size="mini" type="success" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="page-wrapper">
            <el-pagination @current-change="handleCurrentChange" :current-page.sync="form.pagenum" background small :page-size="form.pagesize" :pager-count="5" layout="pager, prev, next, total" :total="total"></el-pagination>
        </div>
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="45%">
            <el-form :model="form" ref="post" :rules="rules" label-width="100px">
                <el-form-item label="页面名称">
                    <el-input v-model="post.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="页面路径">
                    <el-input v-model="post.url" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="活动描述">
                    <el-input v-model="post.desc" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="活动类型">
                    <el-input v-model="post.type" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="资源文件" prop="app_icon">
                    <el-upload
                        drag
                        multiple
                        name="binfile"
                        :action="`${window.location.protocol}//${window.location.host}/api/v1/evm_store/upload`"
                        :on-remove="handleRemove"
                        :on-success="handleSuccess"
                        :file-list="fileList"
                    >
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" size="mini" plain @click="submitForm('post')">提交</el-button>
                <el-button type="success" size="mini" plain @click="onReset('post')">重置</el-button>
                <el-button size="mini" @click="dialogVisible = false">关闭</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { getFrameworkList, deleteFramework, addFramework, updateFramework } from '@/api/app-store'
import { mapTrim, compareObjectDiff, checkURL } from '@/utils/index'
import { formatUTCDateTime } from '@/utils/utils'
export default {
    name: "Framework",
    data() {
        return {
            total: 0,
            list: [],
            form: {
                uuid: null,
                name: null,
                pagesize: 15,
                pagenum: 1
            },
            isLoading: false,
            dialogTitle: "",
            dialogVisible: false,
            currentValue: null,
            currentIndex: null,
            fileList: [],
            post: {
                name: null,
                url: null,
                desc: null,
                type: null,
                assets: {
                    files: []
                }
            },
            rules: {
                permission: [{ type: 'string', required: true, message: '权限名称不能为空', trigger: 'blur' }],
                name: [
                    { type: 'string', required: true, message: '用户名不能为空', trigger: 'blur' },
                    { min: 1, max: 20, message: '字符串长度在 1 到 20 之间', trigger: 'blur' }
                ]
            }
        }
    },
    computed: {
        window: () => window
    },
    methods: {
        fetchData(params) {
            this.isLoading = true
            getFrameworkList(Object.assign({
                pagenum: this.form.pagenum,
                pagesize: this.form.pagesize,
            }, params)).then(res => {
                if (res.code == 200) {
                    this.total = res.count
                    this.list = res.data.map(item => {
                        item.create_at = formatUTCDateTime(item.create_at)
                        item.update_at = formatUTCDateTime(item.update_at)
                        return item
                    })
                }
            }).catch(err => {
                // this.$message.error(err.message)
                console.log(err.message)
            }).finally(() => {
                this.isLoading = false
            })
        },
        fetchSelectData() {
            getFrameworkList({ "scope_type": "list" }).then(res => {
                if (res.code == 200) this.roles = res.data
            }).catch(err => {
                // this.$message.error(err.message)
                console.log(err.message)
            })
        },
        handleSizeChange(e) {
            this.form.pagesize = e
            this.fetchData(mapTrim(this.form))
        },
        handleCurrentChange(e) {
            this.form.pagenum = e
            this.fetchData(mapTrim(this.form))
        },
        handleEdit(index, row) {
            this.post.name = row.name
            this.post.url = row.url
            this.post.desc = row.desc
            this.post.type = row.type
            this.currentValue = row
            this.currentIndex = index
            this.dialogTitle = "编辑"
            this.dialogVisible = true
        },
        handleDelete(index, row) {
            this.$alert('您确定要删除么？删除操作将不可恢复。如需取消操作，请点击右上角关闭按钮。', '删除提醒', {
                confirmButtonText: '确定',
                callback: action => {
                    if (action == 'confirm') deleteFramework(row.uuid).then(res => {
                        console.log(res)
                        // this.total -= 1
                        // this.$delete(this.list, index)
                        this.fetchData(mapTrim(this.form))
                        this.$message({ type: 'success', message: `成功删除第${ index }行` })
                    }).catch(err => {
                        this.$message.error(err.message)
                    })
                }
            })
        },
        handleRemove() {},
        handleSuccess(res) {
            if (res.code == 200) {
                if (!checkURL(res.data.filepath))
                    res.data.filepath = `${window.location.origin}/${res.data.filepath}`
                this.post.assets.files.push(res.data.filepath)
            }
        },
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                let result = true
                if (valid) {
                    if (this.dialogTitle === '添加') addFramework(this.post).then(res => {
                        this.$message({ type: 'success', message: res.message })
                        this.fetchData(mapTrim(this.form))
                    }).catch(err => {
                        this.$message.error(err.message)
                    })
                    else if (this.dialogTitle === '编辑') updateFramework(this.currentValue.uuid, compareObjectDiff(this.post, this.currentValue)).then(res => {
                        // this.$set(this.list, this.currentIndex, Object.assign(this.currentValue, tmp))
                        this.$message({ type: 'success', message: res.message })
                        this.fetchData(mapTrim(this.form))
                    }).catch(err => {
                        this.$message.error(err.message)
                    })
                } else {
                    result = false
                }
                this.dialogVisible = false
                return result
            })
        },
        onAdd() {
            this.dialogTitle = "添加"
            this.dialogVisible = true
        },
        onSubmit() {
            this.form.pagenum = 1
            this.form.pagesize = 15
            this.fetchData(mapTrim(this.form))
        },
        onReset(formName) {
            this.form.name = null
            this.form.pagesize = 15,
            this.form.pagenum = 1
            this.$refs[formName].resetFields()
            this.fetchData()
        }
    },
    mounted() {},
    created() {
        if (this.$store.getters.role !== "ADMIN") this.$router.push({ path: "/403" })
        this.fetchData()
        this.fetchSelectData()
    }
}
</script>
<style lang="less" scoped>
.app-container {
    & > div.page-wrapper {
        margin: 10px 0px;
    }
}
</style>
