<template>
    <div>
        <!-- 细分产业管理 -->
        <!-- 表单查询项 -->
        <div class="headerbox">
            <el-form ref="queryForm" :model="queryParams" size="small" label-width="100px" style="margin-left: -30px;">
                <el-row>
                    <el-col :span="5">
                        <el-form-item label="产业类别" prop="cylb">
                            <el-select v-model="queryParams.cylb" placeholder="请选择产业类别">
                                <el-option v-for="dict in dict.type.cylb" :key="dict.value" :label="dict.label"
                                    :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="产业细分" prop="cyxf" style="width: 100%;">
                            <el-input v-model="queryParams.cyxf" placeholder="请输入产业细分"
                                :fetch-suggestions="querySearchAsync" @keyup.enter.native="handleQuery" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="上楼适应性" prop="slsyx">
                            <el-select v-model="queryParams.slsyx" placeholder="请选择上楼适应性" clearable
                                style="width: 20rem;">
                                <el-option v-for="dict in dict.type.slsyx" :key="dict.value" :label="dict.label"
                                    :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="3">
                        <el-form-item label="更新时间" prop="updateTime">
                            <el-date-picker v-model="queryParams.startTime" type="datetime" format="yyyy-MM-dd HH:mm:ss"
                                value-format="yyyy-MM-dd HH:mm:ss" :style="{ width: '18rem' }" placeholder="选择日期时间"
                                clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item style="margin-left: -70px;">
                            <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
                            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <!-- 表格内容区 -->
        <div class="tablebox">
            <!-- 导出行 -->
            <div class="tablebtntwo">
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
                    </el-col>
                </el-row>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" icon="el-icon-download" @click="handleImport">导入</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="primary" icon="el-icon-upload2" @click="handleExport">全量导出</el-button>
                    </el-col>
                </el-row>
            </div>
            <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
                <!-- <el-table-column type="selection" width="55" align="center" /> -->
                <el-table-column label="序号" width="60" align="center">
                    <template slot-scope="scope">
                        {{ (queryParams.current - 1) * queryParams.size + scope.$index + 1 }}
                    </template>
                </el-table-column>
                <el-table-column label="产业类别" align="center" prop="cylb">
                    <template slot-scope="scope">
                        <dict-tag :options="dict.type.cylb" :value="scope.row.cylb" />
                    </template>
                </el-table-column>
                <el-table-column label="产业细分" align="center" prop="cyxf" />
                <el-table-column label="原材料及生产环节" align="center" prop="ycljschj" />
                <el-table-column label="上楼适应性" align="center" prop="slsyx">
                    <template slot-scope="scope">
                        <dict-tag :options="dict.type.slsyx" :value="scope.row.slsyx" />
                    </template>
                </el-table-column>
                <el-table-column label="更新时间" align="center" prop="updateTime" width="180" />
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" >
                    <template slot-scope="scope">
                        <el-button type="text" @click="handleUpdate(scope.row)">编辑</el-button>
                        <el-button type="text" @click="handleDelete(scope.row)" style="color: red;">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.current"
                :limit.sync="queryParams.size" @pagination="getList" />
        </div>

        <!-- 添加或修改项目对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="40rem" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="160px">
                <el-form-item label="产业类别" prop="cylb" style="width: 100%;">
                    <el-select v-model="form.cylb" placeholder="请选择产业类别" style="width: 100%;">
                        <el-option v-for="dict in dict.type.cylb" :key="dict.value" :label="dict.label"
                            :value="dict.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="产业细分" prop="cyxf">
                    <el-input v-model="form.cyxf" placeholder="请输入产业细分" />
                </el-form-item>
                <el-form-item label="原材料及生产环节" prop="ycljschj">
                    <el-input v-model="form.ycljschj" placeholder="请输入原材料及生产环节" />
                </el-form-item>
                <el-form-item label="上楼适应性" prop="slsyx">
                    <el-select v-model="form.slsyx" placeholder="请选择上楼适应性" style="width: 100%;">
                        <el-option v-for="dict in dict.type.slsyx" :key="dict.value" :label="dict.label"
                            :value="parseInt(dict.value)"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 导入对话框 -->
        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
            <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
                        @click="importTemplate">下载模板</el-link>
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { getXfcyglPage, addXfcygl, updateXfcygl, deleteXfcygl } from "@/api/ManageApi/index";
import fileload from "@/components/FileUpload/index.vue"

export default {
    dicts: ['cylb', 'slsyx'],
    components: {
        fileload
    },
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 目录表格数据
            postList: [],
            // 弹出层标题
            title: "",
            // 是否显示添加或修改弹出层
            open: false,
            // 是否显示详情弹出层
            detailOpen: false,
            // 查询参数
            queryParams: {
                current: 1,
                size: 10,
                cyxf: undefined,
                cylb: undefined,
                slsyx: undefined,
            },
            // 表单参数
            form: {
                cyxf: undefined,
                cylb: undefined,
                ycljschj: undefined,
                slsyx: undefined,
                endTime: undefined,
                startTime: undefined
            },
            // 表单校验
            rules: {
                cyxf: [
                    { required: true, message: "产业细分不能为空", trigger: "blur" }
                ],
                cylb: [
                    { required: true, message: "产业类别不能为空", trigger: "change" }
                ],
                slsyx: [
                    { required: true, message: "上楼适应性不能为空", trigger: "blur" }
                ],
                ycljschj: [
                    { required: true, message: "原材料及生产环节不能为空", trigger: "change" }
                ]
            },
            upload: {
                // 是否显示弹出层（用户导入）
                open: false,
                // 弹出层标题（用户导入）
                title: "细分产业导入",
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的用户数据
                updateSupport: 0,
                // 设置上传的请求头部
                headers: { Authorization: "Bearer " + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + "/gysl/xfcygl/imporXfcy",
            },
        };
    },
    created() {
        this.getList();
    },
    methods: {
        /**导出 */
        handleExport() {
            this.download(
                "/gysl/xfcygl/exportXfcy",
                {
                    ...this.form,
                },
                `细分产业管理${new Date().getTime()}.xlsx`
            );
        },

        querySearchAsync(queryString, cb) {
            let results = [];
            getXfcyglPage({ cyxf: queryString }).then(res => {
                res.data.records.forEach(item => {
                    results.push({
                        value: item.cyxf,
                        id: item.id,
                    });
                });

            });
            cb(results);
        },
        // 查询目录列表
        getList() {
            this.loading = true;
            getXfcyglPage(this.queryParams).then(response => {
                this.postList = response.data.records.map(item => ({
                    ...item,
                }));
                this.total = response.data.total;
                this.loading = false;
            }).catch(error => {
                console.error('API Request Error:', error);
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: undefined,
                cyxf: undefined,
                cylb: undefined,
                ycljschj: undefined,
                slsyx: undefined,
                createBy: undefined,
                createId: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateId: undefined,
                updateTime: undefined,
                startTime: undefined
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.current = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "新增细分产业";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const catalogId = row.id;
            this.form = { ...row };
            this.open = true;
            this.title = "编辑细分产业";
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.id !== undefined) {
                        updateXfcygl(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        }).catch(error => {
                            console.error('API Request Error:', error);
                        });
                    } else {
                        addXfcygl(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        }).catch(error => {
                            console.error('API Request Error:', error);
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const catalogIds = row.id || this.ids;
            this.$modal.confirm('是否确认删除该数据项？').then(() => {
                return deleteXfcygl([catalogIds]);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },
        // 导入操作
        handleImport() {
            this.upload.open = true;
        },
        /** 下载模板操作 */
        importTemplate() {
            this.download(
                "/gysl/xfcygl/importTemplate",
                {},
                `细分产业模板${new Date().getTime()}.xlsx`
            );
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true;
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.open = false;
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();
            this.$alert(
                "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
                response.msg +
                "</div>",
                "导入结果",
                { dangerouslyUseHTMLString: true }
            );
            this.getList();
        },
        // 提交上传文件
        submitFileForm() {
            this.$refs.upload.submit();
        },
    }
};
</script>

<style scoped>
.headerbox {
    background-color: #fff;
    border-radius: .5rem;
    padding: 1rem;
    margin: .5rem;
    border: 1px solid #eee;
}

.tablebox {
    background-color: #fff;
    border-radius: .5rem;
    padding: 1rem;
    margin: .5rem;
    border: 1px solid #eee;
}

.tablehead {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.headbtn {
    display: flex;
}

.tablebtntwo {
    margin-top: 1rem;
    margin-bottom: 1rem;
    width: 100%;
    display: flex;
    justify-content: space-between;
}
</style>