<!-- 企业项目 -->
<template>
    <div class="content">
        <div v-loading.fullscreen.lock="loadingFull" />
        <div class="search_box flexS">
            <div v-for="(item, idx) in categoryList" :key="idx">
                <el-select v-model="params[item.mark]" :placeholder="item.name" class="select" @change="toSearch()"
                    clearable @clear="toSearch()">
                    <el-option v-for="item in item.children" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </div>
            <el-select v-model="params.search_company" placeholder="所属企业" class="select" @change="toSearch()" clearable
                @clear="toSearch()">
                <el-option v-for="item in companyList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
            <el-input v-model="params.search_name" clearable placeholder="项目名称" prefix-icon="el-icon-search"
                @keyup.enter.native="toSearch()" @clear="toSearch()" />
            <el-button type="primary" icon="el-icon-search" :loading="loadingFull" @click="toSearch()">搜索</el-button>

            <el-button @click="handleEdit(false)" type="primary" style="margin-right:10px;">添加</el-button>
            <el-upload class="upload-demo" action="" :http-request="uploadFile" :multiple="false" :show-file-list="false">
                <el-button type="primary">导入</el-button>
            </el-upload>
        </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="name" label="名称" align="center" />
                <el-table-column prop="type" label="分类" align="center">
                    <template slot-scope="{ row }">
                        <span>{{ row.type && row.type.name }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="company_id" label="所属企业" align="center">
                    <template slot-scope="{ row }">
                        <span>{{ row.company && row.company.name }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="amount" 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="45%">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm">
                <el-form-item label="名称：" prop="name">
                    <el-input v-model="ruleForm.name" placeholder="请输入项目名称" style="width:300px" />
                </el-form-item>
                <el-form-item label="项目金额：" prop="amount">
                    <el-input v-model="ruleForm.amount" placeholder="请输入项目金额" style="width:300px" />
                </el-form-item>
                <el-form-item v-for="(item, i) in categoryList" :key="i" :label="item.name" :prop="item.mark">
                    <el-select v-model="ruleForm[item.mark]" :placeholder="'请选择' + item.name" :ref="'template_' + i"
                        :style="{ width: '300px' }" filterable clearableruleFormruleForm style="width:300px">
                        <el-option v-for="(temp, idx) in item.children" :key="idx" :label="temp.name" :value="temp.id">
                            <span style="float: left" class="span-style">{{ temp.name }}</span>
                            <!-- <span style="float: right" class="span-style-delete" @click.stop="deleteItem(temp)">
                                <i class="el-icon-delete" /></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="company_id">
                    <el-select v-model="ruleForm.company_id" placeholder="请选择所属企业">
                        <el-option v-for="item in companyList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="项目介绍:" prop="introduction" required>
                    <textarea name="" id="" cols="50" rows="10" v-model="ruleForm.introduction"></textarea>
                </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 { projectList, addProject, editProject, deleteProject, importProject, projectCategory, companyAll } from '@/api/company'
import { addCategory, editCategory, deleteCategory } from '@/api/category'
import Tinymce from '@/components/Tinymce'
export default {
    data() {
        return {
            categoryList: [], // 类型列表
            dialogVisible: false,
            loadingFull: false,
            listData: [],
            listDataTotal: 0,
            companyList: [], //企业列表
            id: '',// 当前修改公告的id
            isEdit: false,
            ruleForm: {
                name: '',
                company_id: '',
                type: '',
                amount: '',
                introduction: ''
            },
            params: {
                page_index: 1,
                page_size: 10,
                search_name: '',
                search_type: '',
                search_company: ''
            },
            rules: {
                name: [
                    { required: true, message: '请输入项目名称', trigger: 'blur' }
                ],
                amount: [
                    { required: true, message: '请输入项目金额', trigger: 'blur' }
                ],
                company_id: [
                    { required: true, message: '请选择所属企业', trigger: 'change' }
                ],
                type: [
                    { required: true, message: '请选择分类', trigger: 'change' }
                ],
                introduction: [
                    { required: true, message: '请输入项目描述', trigger: 'blur' }
                ]
            }
        }
    },
    mounted() {
        this.getList()
        this.getCompany()
        this.getCategory()
    },
    components: { Tinymce },
    methods: {
        // 获取企业列表
        async getCompany() {
            try {
                const res = await companyAll()
                const { msg, code, data } = res
                if (code === 200) {
                    this.companyList = data
                } else {
                    this.$message.error(msg)
                }
            } catch (e) {
                console.log(`获取列表失败:${e}`)
            }
        },
        // 修改类型
        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() {
            try {
                const res = await projectCategory()
                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()
        },
        // 导入
        uploadFile(params) {
            const file = params.file
            var formData = new FormData()
            formData.append('file', file)
            const isExcel = file.name.endsWith('.xlsx') || file.name.endsWith('.xls')
            console.log(file.name, 'file')
            if (!isExcel) {
                this.$message.error('仅支持上传 .xlsx 或 .xls 格式的文件!')
                return
            }
            importProject(formData).then(res => {
                if (res.code === 200) {
                    this.$message.success('导入成功！')
                    this.getList()
                } else {
                    this.$message.error(res.message || '导入失败！')
                }
            })
        },
        reset() {
            this.ruleForm = {
                name: '',
                company_id: '',
                type: '',
                amount: '',
                introduction: ''
            }
        },
        // 编辑或者添加人才信息
        handleEdit(isEdit, row) {
            this.dialogVisible = true
            this.isEdit = isEdit
            if (!isEdit) { // 添加
                this.reset()
            } else { // 编辑
                this.id = row.id
                const { name, company_id, amount, introduction } = row
                this.ruleForm = {
                    name,
                    company_id,
                    amount,
                    introduction,
                    type: row.type && row.type.id
                }
            }
        },
        // 获取列表
        async getList() {
            this.loadingFull = true
            try {
                const res = await projectList(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) {
                    const http = this.isEdit ? editProject : addProject
                    const { name, company_id, type, amount, introduction } = this.ruleForm
                    const data = this.isEdit ? { name, company_id, type, amount, introduction, id: this.id } : this.ruleForm
                    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 deleteProject({ 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>