<!-- 企业产品 -->
<template>
    <div class="content">
        <div v-loading.fullscreen.lock="loadingFull" />
        <div class="search_box flexS">
            <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="company_id" label="所属企业" align="center">
                    <template slot-scope="{ row }">
                        <span>{{ row.company && row.company.name }}</span>
                    </template>
                </el-table-column>
                <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="img">
                    <el-upload ref="bannerUpload" multiple :limit="15" action="" :show-file-list="false"
                        :http-request="bannerPictureUpload">
                        <el-button size="mini">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">
                            (建议尺寸画布600*480，大小50K)
                        </div>
                    </el-upload>
                    <div class="flexS" style="flex-wrap: wrap;" v-if="ruleForm.img.length > 0">
                        <div v-for="(item, i) in ruleForm.img" :key="i" class="banner_item">
                            <el-image :src="item" style="width: 100px;height: 100px;margin:0 10px 0 10px;"
                                :preview-src-list="ruleForm.img" />
                            <i class="el-icon-delete" @click="deleteBanner(i)" /></span>
                        </div>
                    </div>
                </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="feature" required>
                    <textarea name="" id="" cols="100" rows="5" v-model="ruleForm.feature"></textarea>
                </el-form-item>
                <el-form-item label="研究成果:" prop="achievement" required>
                    <textarea name="" id="" cols="100" rows="5" v-model="ruleForm.achievement"></textarea>
                </el-form-item>
                <el-form-item label="专利技术:" prop="tech" required>
                    <textarea name="" id="" cols="100" rows="5" v-model="ruleForm.tech"></textarea>
                </el-form-item>
                <el-form-item label="使用领域:" prop="field" required>
                    <textarea name="" id="" cols="50" rows="5" v-model="ruleForm.field"></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 { productList, addProduct, editProduct, deleteProduct, importProduct, ProductCategory, companyAll } from '@/api/company'
import { uploadFile } from '@/api/upload'
import Tinymce from '@/components/Tinymce'
export default {
    data() {
        return {
            options: [], // 顶部下拉框选项
            categoryList: [], // 类型列表
            dialogVisible: false,
            loadingFull: false,
            listData: [],
            listDataTotal: 0,
            companyList: [], // 企业列表
            id: '', // 修改当前项目id
            isEdit: false,
            ruleForm: {
                name: '',
                img: [],
                company_id: '',
                feature: '',
                achievement: '',
                tech: '',
                field: ''
            },
            params: {
                page_index: 1,
                page_size: 10,
                search_name: '',
                search_company: ''
            },
            rules: {
                name: [
                    { required: true, message: '请输入产品名称', trigger: 'blur' }
                ],
                company_id: [
                    { required: true, message: '请选择所属企业', trigger: 'change' }
                ],
                feature: [
                    { required: true, message: '请输入产品功能', trigger: 'blur' }
                ],
                achievement: [
                    { required: true, message: '请输入研究成果', trigger: 'blur' }
                ],
                tech: [
                    { required: true, message: '请输入专利技术', trigger: 'blur' }
                ],
                field: [
                    { required: true, message: '请输入使用领域', trigger: 'blur' }
                ],
            }
        }
    },
    mounted() {
        this.getList()
        this.getCompany()
    },
    components: { Tinymce },
    methods: {
        // 轮播图上传
        bannerPictureUpload(params) {
            this.thumbLoad = true
            const file = params.file
            const imgType = ['image/png', 'image/jpg', 'image/jpeg']
            if (imgType.indexOf(file.type) === -1) {
                this.$message.warning('上传图片格式必须为: png或jpg格式')
                return false
            }
            const formData = new FormData()
            formData.append('file', file)
            formData.append('dir', 'image/product')
            uploadFile(formData)
                .then(res => {
                    this.thumbLoad = false
                    try {
                        const { message, code, data } = res
                        if (code === 200) {
                            // 域名/storage/ 拼接
                            this.ruleForm.img.push('http://api.xysyszhd.dev.xmnk.cn/storage/' + data)
                        } else {
                            this.$message.error(message)
                        }
                    } catch (e) {
                        console.log(`上传轮播图失败: ${e}`)
                    }
                })
                .catch(() => {
                    this.thumbLoad = false
                })
        },
        // 删除某一个轮播图
        deleteBanner(i) {
            this.ruleForm.img.splice(i, 1)
        },
        // 获取企业列表
        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}`)
            }
        },
        // 搜索
        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
            }
            importProduct(formData).then(res => {
                if (res.code === 200) {
                    this.$message.success('导入成功！')
                    this.getList()
                } else {
                    this.$message.error(res.message || '导入失败！')
                }
            })
        },
        reset() {
            this.ruleForm = {
                name: '',
                img: [],
                company_id: '',
                feature: '',
                achievement: '',
                tech: '',
                field: ''
            }
        },
        // 编辑或者添加人才信息
        handleEdit(isEdit, row) {
            this.dialogVisible = true
            this.isEdit = isEdit
            if (!isEdit) { // 添加
                this.reset()
            } else { // 编辑
                this.id = row.id
                const { name, img, company_id, feature, achievement, tech, field } = row
                this.ruleForm = {
                    name,
                    company_id,
                    img,
                    feature,
                    achievement,
                    tech,
                    field
                }
            }
        },
        // 获取列表
        async getList() {
            this.loadingFull = true
            try {
                const res = await productList(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 ? editProduct : addProduct
                    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 deleteProduct({ 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;
}

.el-drawer__body {
    overflow-y: scroll;
}
</style>