<!-- 动态模块 -->
<template>
    <div class="content">
        <div v-loading.fullscreen.lock="loadingFull" />
        <div class="search_box">
            <el-button @click="handleEdit(0)" type="primary" style="margin-right:24px;">添加</el-button>
            <el-button @click="reset(), intrDialogVisible = true, isEdit = false" type="primary"
                style="margin-right:24px;">添加行业简介</el-button>
        </div>
        <div class="table_box">
            <el-table ref="list" :data="listData" align="center" :header-cell-style="{ background: '#f8fbfc' }"
                class="tableBorder" border stripe>
                <el-table-column prop="title" label="标题" align="center" />
                <el-table-column label="操作" align="center" width="280">
                    <template slot-scope="{row}">
                        <el-button type="text" size="mini" @click="handleEdit(true, row)">编辑</el-button>
                        <el-button type="text" size="mini" @click="handleDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <el-drawer :title="isEdit ? '修改' : '添加'" :visible.sync="dialogVisible" size="50%">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm">
                <el-form-item label="标题：" prop="title">
                    <el-input v-model="ruleForm.title" placeholder="请输入标题" style="width:300px" />
                </el-form-item>
                <el-form-item label="内容:" prop="content" required>
                    <tinymce v-model="ruleForm.content" :height="300" width="85%" :showUpload="false" />
                </el-form-item>
                <el-form-item>
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="submitForm('ruleForm')">{{ !isEdit ? '确 定' : '保存' }}</el-button>
                </el-form-item>
            </el-form>

        </el-drawer>
        <el-drawer :title="isEdit ? '修改' : '添加'" :visible.sync="intrDialogVisible" size="50%">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm">
                <el-form-item label="标题：" prop="title" v-if="isEdit">
                    <el-input v-model="ruleForm.title" placeholder="请输入标题" style="width:300px" disabled />
                </el-form-item>
                <el-form-item v-for="(item, i) in categoryList  " :key="i" :label="item.name" :prop="item.mark"
                    v-if="!isEdit">
                    <el-select v-model="ruleForm[item.mark]" :placeholder="'请选择' + item.name" :ref="'template_' + i"
                        :style="{ width: '300px' }" filterable clearableruleFormruleForm style="width:300px"
                        @change="handleChange" value-key="id" :disabled="isEdit ? true : false">
                        <el-option v-for="(  temp, idx  ) in   item.children  " :key="idx" :label="temp.name" :value="temp">
                            <span style="float: left" class="span-style">{{ temp.name }}</span>
                            <span style="float: right;margin-left:5px;" class="span-style"
                                @click.stop="editItem(item.id, 1, temp, i)">
                                <i class="el-icon-edit-outline" />
                            </span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="内容:" prop="content" required>
                    <tinymce v-model="ruleForm.content" :height="300" width="85%" :showUpload="false" />
                </el-form-item>
                <el-form-item>
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="submitForm('ruleForm')">{{ !isEdit ? '确 定' : '保存' }}</el-button>
                </el-form-item>
            </el-form>

        </el-drawer>
        <div class="paging_box">
            <pagination :total="listDataTotal" :limit="params.page_size" :page="params.page_index"
                @pagination="changePagination" @update:limit="changePagination" />
        </div>
    </div>
</template>
<script>
import { moduleList, addModule, editModule, deleteModule, moduleCategory } from '@/api/module'
import Tinymce from '@/components/Tinymce'
import { addCategory, editCategory, deleteCategory } from '@/api/category'
export default {
    data() {
        return {
            isIntr: false,
            categoryList: [], // 类型列表
            dialogVisible: false,
            intrDialogVisible: false,
            loadingFull: false,
            listData: [],
            listDataTotal: 0,
            id: '',// 当前修改公告的id
            isEdit: false,
            ruleForm: {
                title: '',
                content: '',
                industry: '',
                mark: ''
            },
            params: {
                page_index: 1,
                page_size: 10,
                search: '',
                type: ''
            },
            rules: {
                title: [
                    { required: true, message: '请输入标题', trigger: 'blur' }
                ],
                content: [
                    { required: true, message: '请输入内容', trigger: 'blur' }
                ],
                industry: [
                    { required: true, message: '请选择行业类型', trigger: 'change' }
                ]
            }
        }
    },
    mounted() {
        this.getList()
        this.getCategory()
    },
    components: { Tinymce },
    methods: {
        handleChange(e) {
            console.log(e, 'e')
            this.ruleForm.title = e.name
        },
        // 修改类型
        editItem(fid, isEdit, info, idx) {
            this.addItem(fid, isEdit, info, idx)
        },
        // 添加/修改类型
        addItem(fid, isEdit, info, idx) {
            if (info && info != null && isEdit === 1) {
                this.$message.error('无可编辑内容')
                return
            }
            let val = ''
            if (info) {
                const index = this.categoryList[idx].children.findIndex((e) => e.id === info.id)
                const obj = this.categoryList[idx].children[index]
                val = obj.name
            }
            this.$prompt(' 请输入新的类型名称 ', isEdit === 1 ? '编辑' : '添加', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputValue: val
            }).then(async ({ value }) => {
                if (!value || value === '') {
                    this.$message.error('类型名称不能为空!')
                } else {
                    const http = isEdit === 1 ? editCategory : addCategory
                    const data = isEdit === 1 ? { fid, id: info.id, name: value } : { fid, name: value }
                    http(data).then(res => {
                        if (res.code === 200) {
                            this.$message.success(isEdit === 1 ? '修改类型成功' : '添加类型成功')
                            this.getCategory()
                        } else {
                            this.$message.success(res.msg || isEdit === 1 ? '修改类型失败' : '添加类型失败')
                        }
                    })
                }
            })
        },
        // 删除类型
        deleteItem(info) {
            this.$confirm("确定要删除" + "' " + info.name + " '" + "吗？", "删除", {
                type: 'warning'
            })
                .then(() => {
                    // 本地静态删除
                    deleteCategory({ id: info.id }).then(res => {
                        if (res.code === 200) {
                            this.$message.success('删除成功')
                            this.getCategory()
                        } else {
                            this.$message.error(res.message || '删除失败')
                        }
                    })
                })
                .catch(() => { });
        },
        // 下拉时显示底下的新增按钮
        visibleChange(visible, refName, fid) {
            if (visible) {
                const ref = this.$refs[refName][0];
                let product = ref.$refs.popper;
                if (product.$el) product = product.$el;
                if (
                    !Array.from(product.children).some(
                        (v) => v.className === "el-template-menu__list"
                    )
                ) {
                    const el = document.createElement("ul");
                    el.className = "el-template-menu__list";
                    el.style =
                        "border-top:2px solid rgb(219 225 241); padding:0; color:rgb(64 158 255);font-size: 13px";
                    el.innerHTML = `<li class="el-cascader-node text-center" style="height:37px;line-height: 50px;margin-left:10px;">
              <span class="el-cascader-node__label"><i class="font-blue el-icon-plus"></i> 新增公告</span>
              </li>`;
                    product.appendChild(el);
                    // 新增按钮点击事件
                    el.onclick = () => {
                        this.addItem(fid, 0);
                    };
                }
            }
        },
        // 获取分类列表
        async getCategory() {
            this.options = []
            try {
                const res = await moduleCategory()
                const { message, code, data } = res
                if (code === 200) {
                    this.categoryList = data
                } else {
                    this.$message.error(message)
                }
            } catch (e) {
                console.log(`获取列表失败:${e}`)
            }
        },
        // 搜索
        toSearch() {
            this.params.page_index = 1
            this.getList()
        },
        reset() {
            this.ruleForm = {
                title: '',
                content: '',
                mark: '',
                industry: ''
            }
        },
        // 编辑或者添加信息
        handleEdit(isEdit, row) {
            this.isEdit = isEdit
            if (!isEdit) { // 添加
                this.reset()
                this.dialogVisible = true
            } else { // 编辑
                this.id = row.id
                const { title, content, mark } = row
                if (row.mark) {
                    this.intrDialogVisible = true
                } else {
                    this.dialogVisible = true
                }

                this.ruleForm = {
                    title,
                    content,
                    mark
                }
            }
        },
        // 获取列表
        async getList() {
            this.loadingFull = true
            try {
                const res = await moduleList(this.params)
                const { message, code, data } = res
                if (code === 200) {
                    const { list, total } = data
                    this.listData = list
                    this.listDataTotal = total
                } else {
                    this.$message.error(message)
                }
            } catch (e) {
                console.log(`获取列表失败:${e}`)
                this.loadingFull = false
            }
            this.loadingFull = false
        },
        // 添加/编辑事件
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.ruleForm.mark = 'industry-' + this.ruleForm.industry
                    const http = this.isEdit ? editModule : addModule
                    const { title, content, mark } = this.ruleForm
                    const data = this.isEdit ? { title, content, mark, id: this.id } : { title, content, mark }
                    http(data).then(res => {
                        if (res.code === 200) {
                            this.$message.success(this.isEdit ? '修改成功！' : '添加成功!')
                            this.getList()
                            this.dialogVisible = false
                        } else {
                            this.$message.error(this.isEdit ? '修改失败！' : '添加失败!')
                            this.$message.error(res.msg)
                        }
                    })
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        },
        // 删除确认
        handleDelete(row) {
            const { id } = row
            this.$confirm('确认要删除该信息吗?', '删除确认', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.deleteEvent(id)
            })
        },
        // 删除事件
        async deleteEvent(id) {
            const res = await deleteModule({ id })
            try {
                const { message, code } = res
                if (code === 200) {
                    this.$message.success('删除成功！')
                    this.getList()
                } else {
                    this.$message.error(message)
                }
            } catch (e) {
                this.$message.error(e.message)
            }
        },
        // 分页页码变化
        changePagination(data) {
            const { page, limit } = data
            this.params.page_size = limit
            this.params.page_index = page
            this.getList()
        }
    }

}
</script>
<style lang="scss" scoped>
.el-input,
textarea {
    width: 350px;
}
</style>