<template>
    <div class="container">
        <el-form inline size="small">
            <el-form-item label="数据年份:" label-width="80px">
                <el-select v-model="queryForm.year" :popper-append-to-body="false" @change="initTemplate">
                    <el-option v-for="item in yearDict" :key="item.id" :label="item.label" :value="item.value">
                        <span style="float: left">{{ item.label }}</span>
                        <i class="el-icon-delete option_icon" style="color: #F56C6C;"
                           @click.stop="deleteYear(item)"
                        ></i>
                        <i class="el-icon-edit-outline option_icon" style="color: #8492a6;"
                           @click.stop="editYearDialog(item)"
                        ></i>
                    </el-option>
                </el-select>
                <i class="el-icon-circle-plus-outline form_icon" @click="openYearDialog"></i>
            </el-form-item>
            <el-form-item label="数据类型:" label-width="80px">
                <el-select v-model="queryForm.orgName" :popper-append-to-body="false">
                    <el-option v-for="item in orgDict" :key="item.id" :label="item.label" :value="item.value">
                        <span style="float: left">{{ item.label }}</span>
                        <i class="el-icon-delete option_icon" style="color: #F56C6C;" @click.stop="deleteOrg(item)"></i>
                        <i class="el-icon-edit-outline option_icon" style="color: #8492a6;"
                           @click.stop="editOrgDialog(item)"
                        ></i>
                    </el-option>
                </el-select>
                <i class="el-icon-circle-plus-outline form_icon" @click="openOrgDialog"></i>
            </el-form-item>
            <el-form-item label="请选择导入文件:" label-width="120px">
                <el-upload ref="upload" :auto-upload="false" :http-request="fileUpload" :on-change="fileChange"
                           :on-remove="fileRemove"
                           action="xxx" class="upload" multiple
                >
                    <el-button size="small" plain>选择文件</el-button>
                </el-upload>
            </el-form-item>
            <el-form-item>
                <el-button :loading="importLoading" icon="el-icon-upload" plain size="small"
                           @click="triggerImport"
                >导入数据
                </el-button>
            </el-form-item>
        </el-form>
        <el-divider class="divider1"></el-divider>
        <el-form inline size="small">
            <el-form-item>
                <el-button style="margin-left:6px;" size="small" icon="el-icon-pie-chart" plain>分析并导出</el-button>
                <el-button size="small" icon="el-icon-set-up" plain>设置机构字典</el-button>
                <el-button size="small" icon="el-icon-refresh" plain>清空数据</el-button>
                <el-button icon="el-icon-folder-add" plain size="small" @click="openTemplateDialog">添加模板</el-button>
            </el-form-item>
        </el-form>
        <el-table v-loading="queryTemplateLoading" :data="templateList"
                  border stripe style="margin-left:6px;"
        >
            <el-table-column align="center" type="index" width="50"/>
            <el-table-column align="center" label="机构类型" prop="orgName" show-overflow-tooltip/>
            <el-table-column :formatter="importStatusFormat" align="center" label="导入状态" prop="importStatus"
                             show-overflow-tooltip
            />
            <el-table-column :formatter="yearFormat" align="center" label="数据年份" prop="year" show-overflow-tooltip/>
            <el-table-column align="center" label="导入时间" prop="importTime" show-overflow-tooltip/>
            <el-table-column :formatter="templateStatusFormat" align="center" label="模板状态" show-overflow-tooltip/>
            <el-table-column align="center" label="操作" width="190">
                <template slot-scope="scope">
                    <el-button circle icon="el-icon-edit" plain
                               size="small" type="primary" @click.stop="editTemplateDialog(scope.row)"
                    ></el-button>
                    <el-button circle icon="el-icon-delete" plain
                               size="small" type="danger" @click.stop="deleteTemplate(scope.row)"
                    ></el-button>
                    <el-dropdown size="small" style="margin-left: 10px">
                        <el-button plain size="small" type="primary">
                            更多菜单<i class="el-icon-arrow-down el-icon--right"></i>
                        </el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item icon="el-icon-upload2" @click.native="openUploadTemplate(scope.row)">
                                模板上传
                            </el-dropdown-item>
                            <el-dropdown-item icon="el-icon-download">模板下载</el-dropdown-item>
                            <el-dropdown-item icon="el-icon-view" @click.native="openFieldDrawer(scope.row)">查看字段
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </template>
            </el-table-column>
        </el-table>
        <el-divider class="divider2"></el-divider>
        <div style="margin-left:6px;margin-bottom: 8px;">
            <span style="font-size: 14px;color: #E6A23C;">温馨提示：分析后，数据没有问题再往正式库中导入数据！</span>
        </div>
        <el-button icon="el-icon-upload" plain size="small" style="margin-left:6px;" @click="triggerImport">
            一键导入正式库
        </el-button>
        <span></span>
        <!-- 年份字典 -->
        <el-dialog :title="yearDialog.title" :visible.sync="yearDialog.show" close-on-click-modal append-to-body
                   width="400px"
        >
            <el-form ref="yearForm" size="small" :model="yearDialog.data" label-width="50px">
                <el-form-item required prop="label" label="标签">
                    <el-input v-model="yearDialog.data.label"/>
                </el-form-item>
                <el-form-item required prop="value" label="值">
                    <el-input v-model="yearDialog.data.value"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitYear">确 定</el-button>
                <el-button @click="yearDialog.show = false">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 机构类型字典 -->
        <el-dialog :title="orgDialog.title" :visible.sync="orgDialog.show" close-on-click-modal append-to-body
                   width="400px"
        >
            <el-form ref="orgForm" size="small" :model="orgDialog.data" label-width="100px">
                <el-form-item required prop="value" label="机构类型">
                    <el-input v-model="orgDialog.data.value"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitOrg">确 定</el-button>
                <el-button @click="orgDialog.show = false">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 模板信息 -->
        <el-dialog :title="templateDialog.title" :visible.sync="templateDialog.show" append-to-body close-on-click-modal
                   width="400px"
        >
            <el-form ref="templateForm" :model="templateDialog.data" label-width="100px" size="small">
                <el-form-item label="模板名称" prop="name">
                    <el-input v-model="templateDialog.data.name"/>
                </el-form-item>
                <el-form-item label="机构类型" prop="orgName" required>
                    <el-select v-model="templateDialog.data.orgName" :popper-append-to-body="false">
                        <el-option v-for="item in orgDict" :key="item.id" :label="item.label" :value="item.value"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="数据年份" prop="year" required>
                    <el-select v-model="templateDialog.data.year" :popper-append-to-body="false">
                        <el-option v-for="item in yearDict" :key="item.id" :label="item.label" :value="item.value"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="数据源" prop="dataSourceId">
                    <el-select v-model="templateDialog.data.dataSourceId" :popper-append-to-body="false"
                               @change="changeDataSource"
                    >
                        <el-option v-for="item in dataSourceList" :key="item.id" :label="item.label"
                                   :value="item.value"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="数据表" prop="tableName">
                    <el-select v-model="templateDialog.data.tableName" v-loading="queryTableLoading"
                               :loading="queryTableLoading"
                               :popper-append-to-body="false" filterable
                               @change="$forceUpdate()"
                    >
                        <el-option v-for="item in tableList" :key="item.value" :label="item.label" :value="item.value">
                            <el-tooltip :disabled="item.label.length < 17" placement="top">
                                <div slot="content">
                                    <span>{{ item.label }}</span>
                                </div>
                                <div style="max-width: 500px;">{{ item.label }}</div>
                            </el-tooltip>
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitTemplate">确 定</el-button>
                <el-button @click="templateDialog.show = false">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 字段信息 -->
        <el-dialog :title="fieldDialog.title" :visible.sync="fieldDialog.show" append-to-body close-on-click-modal
                   width="400px"
        >
            <el-form ref="fieldForm" :model="fieldDialog.data" label-width="110px" size="small">
                <el-form-item label="代码" prop="code">
                    <el-input v-model="fieldDialog.data.code"/>
                </el-form-item>
                <el-form-item label="指标名称" prop="title" required>
                    <el-input v-model="fieldDialog.data.title"/>
                </el-form-item>
                <el-form-item label="计量单位" prop="unit">
                    <el-input v-model="fieldDialog.data.unit"/>
                </el-form-item>
                <el-form-item label="数据起始坐标" prop="coordinate" required>
                    <el-input v-model="fieldDialog.data.coordinate"/>
                </el-form-item>
                <el-form-item label="排序字段" prop="sort">
                    <el-input-number v-model="fieldDialog.data.sort" :min="0" :precision="0"/>
                </el-form-item>
                <el-form-item label="数据库字段" prop="field">
                    <el-select v-model="fieldDialog.data.field" :popper-append-to-body="false">
                        <el-option v-for="item in fieldDict" :key="item.id" :label="item.label" :value="item.value"
                        ></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitField">确 定</el-button>
                <el-button @click="fieldDialog.show = false">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 字段抽屉 -->
        <el-drawer :visible.sync="fieldDrawer.show" append-to-body
                   destroy-on-close direction="rtl"
                   size="50%" title="字段信息"
        >
            <el-form inline label-width="110px" size="small">
                <el-form-item label="数据库字段名:">
                    <el-input v-model="fieldDrawer.queryForm.field"/>
                </el-form-item>
                <el-form-item label="代码:">
                    <el-input v-model="fieldDrawer.queryForm.code"/>
                </el-form-item>
                <el-form-item label="指标名称:">
                    <el-input v-model="fieldDrawer.queryForm.title"/>
                </el-form-item>
                <el-form-item label="数据坐标:">
                    <el-input v-model="fieldDrawer.queryForm.coordinate"/>
                </el-form-item>
                <el-form-item label="">
                    <el-button :loading="fieldDrawer.queryFieldLoading" icon="el-icon-search" plain type="primary"
                               @click="queryFieldList"
                    >查询
                    </el-button>
                    <el-button plain type="primary" @click="openFieldDialog">新增</el-button>
                    <el-button plain type="primary" @click="openQuicklyBind">快速绑定</el-button>
                </el-form-item>
            </el-form>
            <el-table v-loading="fieldDrawer.queryFieldLoading" :data="fieldDrawer.fieldList"
                      border stripe style="margin-left:6px;"
            >
                <el-table-column align="center" label="代码" prop="code" show-overflow-tooltip/>
                <el-table-column align="center" label="指标名称" prop="title" show-overflow-tooltip/>
                <el-table-column align="center" label="数据坐标" prop="coordinate" show-overflow-tooltip/>
                <el-table-column align="center" label="数据库字段名" prop="field" show-overflow-tooltip/>
                <el-table-column align="center" label="操作" width="150">
                    <template slot-scope="scope">
                        <el-button plain size="small" @click.stop="openRuleBindDialog(scope.row)">规则</el-button>
                        <el-button circle icon="el-icon-edit" plain
                                   size="small" type="primary" @click.stop="editFieldDialog(scope.row)"
                        ></el-button>
                        <el-button circle icon="el-icon-delete" plain
                                   size="small" type="danger" @click.stop="deleteField(scope.row)"
                        ></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="fieldDrawer.queryForm.total > 0" :limit.sync="fieldDrawer.queryForm.pageSize"
                        :page.sync="fieldDrawer.queryForm.pageNum"
                        :total="fieldDrawer.queryForm.total" @pagination="queryFieldList"
            />
        </el-drawer>
        <!-- 快速绑定 -->
        <el-dialog :visible.sync="quicklyBindDialog.show" append-to-body close-on-click-modal title="快速绑定"
                   width="400px"
        >
            <el-form ref="orgForm" label-width="100px" size="small">
                <el-form-item label="规则" prop="ruleId">
                    <el-select v-model="quicklyBindDialog.ruleId" size="small">
                        <el-option v-for="item in ruleDict" :key="item.value" :label="item.label" :value="item.value"/>
                    </el-select>
                </el-form-item>
                <span style="font-size: 13px;color: #F56C6C">设置后将为每一条字段添加此规则!</span>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button :loading="quicklyBindDialog.loading" type="primary" @click="submitQuickBind">确 定
                </el-button>
                <el-button @click="quicklyBindDialog.show = false">取 消</el-button>
            </div>
        </el-dialog>
        <!--字段规则增删改-->
        <el-dialog
            :close-on-click-modal="true"
            :visible.sync="bindDialog.show"
            append-to-body
            title="字段规则绑定"
            width="700px"
        >
            <div>
                <el-transfer
                    v-model="bindDialog.data"
                    v-loading="bindDialog.loading"
                    :button-texts="['移除规则', '添加规则']"
                    :data="ruleDict"
                    :props="{ key: 'value', label: 'label' }"
                    :titles="['全部规则', '已选规则']"
                    filterable
                    style="text-align: left; display: inline-block"
                >
                </el-transfer>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitBindRule">确 定</el-button>
                <el-button @click="bindDialog.show = false">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 模板上传 -->
        <AutoUpload
            ref="initTemplateUpload"
            :accept="['xls', 'xlsx']"
            :multiple="false"
            :open.sync="initTemplateDialog.show"
            title="初始模板上传"
            @upload="initTemplateUpload"
        />
    </div>
</template>

<script>
import * as Emport from '@/api/emport/Emport'
import StringUtil from '@/utils/document/StringUtil'
import AutoUpload from '@/views/emport/emport/AutoUpload.vue'

export default {
    name: 'Emport',
    components: { AutoUpload },
    data() {
        return {
            // 页面查询字段
            queryForm: {
                year: '',
                orgName: '', //数据类型
                file: null
            },
            yearDict: [], // 年份字典
            orgDict: [], // 机构类型字典
            ruleDict: [], // 规则字典
            dataSourceList: [], // 数据源列表
            tableList: [], // 表列表
            fieldDict: [], // 字段字典
            yearDialog: { // 年份dialog
                title: '',
                show: false,
                data: {}
            },
            orgDialog: { // 机构类型dialog
                title: '',
                show: false,
                data: {}
            },
            templateDialog: {
                title: '',
                show: false,
                data: {}
            },
            fieldDialog: { // 字段dialog
                title: '',
                show: false,
                data: {}
            },
            bindDialog: {
                show: false,
                data: [],
                loading: false,
                fieldId: null
            },
            fieldDrawer: { // 字段抽屉
                template: null,
                show: false,
                fieldList: [],
                queryForm: {
                    templateId: '',
                    code: '',
                    title: '',
                    coordinate: '',
                    field: '',
                    pageNum: 1,
                    pageSize: 10,
                    total: 0
                },
                queryFieldLoading: false
            },
            quicklyBindDialog: { // 字段dialog
                show: false,
                ruleId: null,
                loading: false
            },
            initTemplateDialog: {
                template: null,
                show: false
            },
            importLoading: false, // 导入数据loading
            queryTemplateLoading: false, // 模板查询loading
            queryTableLoading: false, // 查询数据表loading
            templateList: [] // 模板列表
        }
    },
    created() {
        this.initYearDict(() => {
            let now = new Date()
            this.queryForm.year = now.getFullYear() + ''
            this.initTemplate()
        })
        this.initOrgDict((list) => {
            if (list && list.length > 0) {
                this.queryForm.orgName = list[0].value
            }
        })
        this.initDataSource()
        this.initRuleDict()
    },
    methods: {
        // 初始化年份字典
        initYearDict(callback) {
            Emport.queryDict('year').then((res) => {
                if (res.code === 200) {
                    this.yearDict = res.data
                    if (callback) callback(res.data)
                }
            })
        },
        // 初始化机构类型字典
        initOrgDict(callback) {
            Emport.queryDict('org').then((res) => {
                if (res.code === 200) {
                    this.orgDict = res.data
                    if (callback) callback(res.data)
                }
            })
        },
        // 初始化数据源字典
        initDataSource() {
            Emport.queryDatasource().then(res => {
                if (res.code === 200) {
                    this.dataSourceList = res.data.map(item => {
                        return {
                            label: item.datasourceName,
                            value: item.datasourceName,
                            id: item.datasourceId
                        }
                    })
                }
            })
        },
        // 初始化规则字典
        initRuleDict() {
            Emport.queryRuleDict().then(res => {
                this.ruleDict = res.data.map(item => {
                    return {
                        value: item.id,
                        label: item.name
                    }
                })
            })
        },
        // 初始化数据表列表
        initTable(datasourceId, callback) {
            this.queryTableLoading = true
            Emport.queryTable(datasourceId)
                .then(res => {
                    if (res.code === 200) {
                        this.tableList = res.data.map(item => {
                            return {
                                value: item.VALUE,
                                label: StringUtil.mergeStr(item.VALUE, item.LABEL)
                            }
                        })
                        if (callback) callback(this.tableList)
                    }
                }).finally(_ => this.queryTableLoading = false)
        },
        // 初始化数据表字段字典
        initFieldDict() {
            if (this.fieldDrawer.template && this.fieldDrawer.template.tableName && this.fieldDrawer.template.dataSourceId) {
                Emport.queryDbField(this.fieldDrawer.template.dataSourceId, this.fieldDrawer.template.tableName)
                    .then(res => {
                        if (res.code === 200) {
                            this.fieldDict = res.data.map(item => {
                                return {
                                    value: item.VALUE,
                                    label: StringUtil.mergeStr(item.VALUE, item.LABEL)
                                }
                            })
                        }
                    })
            }
        },
        // 初始化模板列表
        initTemplate() {
            this.queryTemplateLoading = true
            Emport.queryTemplate({
                year: this.queryForm.year
            })
                .then(res => {
                    if (res.code === 200) {
                        this.templateList = res.data
                    }
                }).finally(_ => this.queryTemplateLoading = false)
        },
        // 打开年份字典新增框
        openYearDialog() {
            this.yearDialog.title = '新增年份'
            this.yearDialog.data = {
                type: 'year',
                label: '', value: ''
            }
            this.yearDialog.show = true
        },
        // 打开年份字典编辑框
        editYearDialog(data) {
            this.yearDialog.title = '编辑年份'
            this.yearDialog.data = { ...data }
            this.yearDialog.show = true
        },
        // 提交年份dialog
        submitYear() {
            this.$refs.yearForm.validate(valid => {
                if (valid) {
                    if (this.yearDialog.title === '新增年份') {
                        Emport.addDict(this.yearDialog.data)
                            .then(res => {
                                this.yearDialog.show = false
                                this.initYearDict()
                            })
                    } else {
                        Emport.updateDict(this.yearDialog.data)
                            .then(res => {
                                this.yearDialog.show = false
                                this.initYearDict()
                            })
                    }
                }
            })
        },
        // 删除年份字典
        deleteYear({ id, label }) {
            this.$confirm(`是否删除数据项 ${label} ?`, '删除',
                {
                    type: 'warning',
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    beforeClose: (action, instance, done) => {
                        if (action === 'confirm') {
                            Emport.deleteDict(id).then(res => {
                                done()
                                this.initYearDict()
                            })
                        } else {
                            done()
                        }
                    }
                }
            )
        },
        // 打开机构类型字典新增框
        openOrgDialog() {
            this.orgDialog.title = '新增机构类型'
            this.orgDialog.data = { type: 'org', value: '' }
            this.orgDialog.show = true
        },
        // 打开机构类型字典编辑框
        editOrgDialog(data) {
            this.orgDialog.title = '编辑机构类型'
            this.orgDialog.data = { ...data }
            this.orgDialog.show = true
        },
        // 提交机构类型dialog
        submitOrg() {
            this.$refs.orgForm.validate(valid => {
                if (valid) {
                    if (this.orgDialog.title === '新增机构类型') {
                        Emport.addDict({
                            ...this.orgDialog.data,
                            label: this.orgDialog.data.value
                        })
                            .then(res => {
                                this.orgDialog.show = false
                                this.initOrgDict()
                            })
                    } else {
                        Emport.updateDict({
                            ...this.orgDialog.data,
                            label: this.orgDialog.data.value
                        })
                            .then(res => {
                                this.orgDialog.show = false
                                this.initOrgDict()
                            })
                    }
                }
            })
        },
        // 删除机构类型字典
        deleteOrg({ id, label }) {
            this.$confirm(`是否删除数据项 ${label} ?`, '删除',
                {
                    type: 'warning',
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    beforeClose: (action, instance, done) => {
                        if (action === 'confirm') {
                            Emport.deleteDict(id).then(res => {
                                done()
                                this.initOrgDict()
                            })
                        } else {
                            done()
                        }
                    }
                }
            )
        },
        // 文件列表发生变化
        fileChange(file, fileList) {
            let fileType = file.name.substring(file.name.lastIndexOf('.') + 1)
            let extension = ['xls', 'xlsx'].some(item => {
                return item === fileType.toLowerCase()
            })
            if (!extension) {
                this.$message.warning(`请选择类型为 xls/xlsx 的文件`)
                fileList.splice(-1, 1) //移除当前选中
                return
            }
            if (fileList.length > 1) {
                fileList.splice(0, 1) //移除选中的第一个
            }
            this.queryForm.file = fileList[0]
        },
        // 文件上传方法
        fileUpload({ file, onError, onProgress, onSuccess }) {
            this.importLoading = true
            let formData = new FormData()
            formData.append('file', file)
            //formData.append("templateId", this.checkTemplate.id);
            Emport.uploadExcel(formData)
                .then((res) => {
                    if (res.code === 200) {
                        onSuccess()
                    } else {
                        onError()
                    }
                })
                .finally((_) => {
                    this.importLoading = false
                })
        },
        // 触发导入
        triggerImport() {
            if (this.queryForm.file) {
                this.$refs.upload.submit()
            } else {
                this.$message.warning('请选择一个文件')
            }
        },
        // 移除文件
        fileRemove() {
            this.queryForm.file = null
        },
        // 打开添加模板dialog
        openTemplateDialog() {
            this.templateDialog.data = {}
            this.templateDialog.title = '添加模板'
            this.templateDialog.show = true
        },
        // 修改数据源
        changeDataSource(value) {
            this.initTable(value, () => {
                this.templateDialog.data.tableName = ''
            })
        },
        // 提交模板dialog
        submitTemplate() {
            this.$refs.templateForm.validate(valid => {
                if (valid) {
                    if (this.templateDialog.title === '添加模板') {
                        Emport.addTemplate(this.templateDialog.data)
                            .then(res => {
                                this.templateDialog.show = false
                                this.initTemplate()
                            })
                    } else {
                        Emport.updateTemplate(this.templateDialog.data)
                            .then(res => {
                                this.templateDialog.show = false
                                this.initTemplate()
                            })
                    }
                }
            })
        },
        // 导入状态格式化
        importStatusFormat(row) {
            if (row.importStatus === '1') {
                return '已导入'
            } else {
                return '未导入'
            }
        },
        // 数据年份格式化
        yearFormat(row) {
            return this.yearDict.find(item => item.value === row.year)?.label
        },
        // 打开模板编辑框
        editTemplateDialog(row) {
            this.templateDialog.title = '编辑模板'
            this.templateDialog.data = { ...row }
            this.templateDialog.show = true
        },
        // 删除模板
        deleteTemplate(row) {
            this.$confirm(`是否删除模板 ${row.orgName} ?`, '删除',
                {
                    type: 'warning',
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    beforeClose: (action, instance, done) => {
                        if (action === 'confirm') {
                            Emport.deleteTemplate(row.id).then(res => {
                                done()
                                this.initTemplate()
                            })
                        } else {
                            done()
                        }
                    }
                }
            )
        },
        // 提交字段dialog
        submitField() {
            this.$refs.fieldForm.validate(valid => {
                if (valid) {
                    if (this.fieldDialog.title === '新增字段') {
                        Emport.addField(this.fieldDialog.data)
                            .then(res => {
                                this.fieldDialog.show = false
                                this.queryFieldList()
                            })
                    } else {
                        Emport.updateField(this.fieldDialog.data)
                            .then(res => {
                                this.fieldDialog.show = false
                                this.queryFieldList()
                            })
                    }
                }
            })
        },
        // 打开字段抽屉
        openFieldDrawer(row) {
            this.fieldDrawer.template = { ...row }
            this.fieldDrawer.queryForm = {
                templateId: row.id,
                code: '',
                title: '',
                coordinate: '',
                field: '',
                pageNum: 1,
                pageSize: 10,
                total: 0
            }
            this.fieldDrawer.fieldList = []
            this.fieldDrawer.show = true
            this.queryFieldList()
            this.initFieldDict()
        },
        // 查询字段列表
        queryFieldList() {
            this.fieldDrawer.queryFieldLoading = true
            Emport.queryField(this.fieldDrawer.queryForm)
                .then(res => {
                    this.fieldDrawer.fieldList = res.rows
                    this.fieldDrawer.queryForm.total = res.total
                }).finally(_ => this.fieldDrawer.queryFieldLoading = false)
        },
        // 打开新增字段dialog
        openFieldDialog() {
            this.fieldDialog.title = '新增字段'
            this.fieldDialog.data = {
                templateId: this.fieldDrawer.template.id
            }
            this.fieldDialog.show = true
        },
        // 打开修改字段的dialog
        editFieldDialog(row) {
            this.fieldDialog.title = '修改字段'
            this.fieldDialog.data = { ...row }
            this.fieldDialog.show = true
        },
        // 删除字段
        deleteField(row) {
            this.$confirm(`是否删除字段 ${StringUtil.mergeStr(row.code, row.title)} ?`, '删除',
                {
                    type: 'warning',
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    beforeClose: (action, instance, done) => {
                        if (action === 'confirm') {
                            Emport.deleteField(row.id).then(res => {
                                done()
                                this.queryFieldList()
                            })
                        } else {
                            done()
                        }
                    }
                }
            )
        },
        // 打开快速绑定dialog
        openQuicklyBind() {
            this.quicklyBindDialog.show = true
            this.quicklyBindDialog.ruleId = null
        },
        // 提交快速绑定
        submitQuickBind() {
            if (this.quicklyBindDialog.ruleId) {
                this.quicklyBindDialog.loading = true
                Emport.quickBind(this.fieldDrawer.template.id, this.quicklyBindDialog.ruleId)
                    .then(res => {
                        if (res.code === 200) {
                            this.$message.success('绑定成功')
                            this.quicklyBindDialog.show = false
                            this.queryFieldList()
                        }
                    }).finally(_ => this.quicklyBindDialog.loading = false)
            }

        },
        // 打开字段规则绑定弹出框
        openRuleBindDialog(row) {
            this.bindDialog.loading = true
            this.bindDialog.show = true
            this.bindDialog.fieldId = row.id
            Emport.queryBindRule(row.id).then(res => {
                if (res.code === 200) {
                    this.bindDialog.data = res.data.map(item => item.id)
                }
            }).finally(_ => this.bindDialog.loading = false)
        },
        // 提交规则绑定数据
        submitBindRule() {
            this.bindDialog.loading = true
            Emport.bindRule({
                fieldId: this.bindDialog.fieldId,
                ruleIdList: this.bindDialog.data
            }).then(res => {
                if (res.code === 200) {
                    this.$message.success('绑定成功')
                    this.bindDialog.show = false
                }
            }).finally(_ => this.bindDialog.loading = false)
        },
        // 模板状态格式化
        templateStatusFormat(row) {
            if (row.excelId) {
                return '已上传'
            } else {
                return '未上传'
            }
        },
        // 打开上传初始模板
        openUploadTemplate(row) {
            this.initTemplateDialog.template = row
            this.initTemplateDialog.show = true
        },
        // 初始化模板上上传方法
        initTemplateUpload({ file, onSuccess }) {
            let formData = new FormData()
            formData.append('file', file)
            formData.append('type', '2')
            formData.append('templateId', this.initTemplateDialog.template.id)
            formData.append('year', this.initTemplateDialog.template.year)
            formData.append('orgName', this.initTemplateDialog.template.orgName)
            Emport.uploadExcel(formData).then(res => {
                if (res.code === 200) {
                    onSuccess()
                    this.$message.success('上传成功')
                    this.initTemplateDialog.show = false
                    this.initTemplate()
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.container {
    .form_icon {
        cursor: pointer;
        color: rgb(170, 173, 179);
        font-size: 18px;
        margin-left: 5px;
        padding-top: 5px;
    }

    .option_icon {
        cursor: pointer;
        font-size: 14px;
        float: right;
        margin-left: 3px;
        margin-top: 10px;
    }

    .divider1 {
        margin: -10px 0 10px 0;
    }

    .divider2 {
        margin: 15px 0 10px 0;
    }

    ::v-deep {
        .upload {
            display: flex;
            align-items: center;
        }

        .el-upload-list__item:first-child {
            margin-top: 0;
        }

        .el-upload-list {
            border: 1px solid #dcdfe6;
            min-width: 100px;
            height: 30px;
            border-radius: 2px;
            overflow-y: hidden;
        }

    }
}
</style>
