<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 icon="el-icon-pie-chart" plain
                           size="small"
                           style="margin-left:6px;" @click="analyzeExport"
                >分析并导出
                </el-button>
                <el-button icon="el-icon-set-up" plain size="small" @click="openOrgDictDialog">设置机构字典</el-button>
                <el-button size="small" icon="el-icon-refresh" plain :loading="clearTempLoading" @click="clearTemp">
                    清空数据
                </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 :disabled="!scope.row.excelId" icon="el-icon-download"
                                              @click.native="downloadTemplate(scope.row)"
                            >模板下载
                            </el-dropdown-item>
                            <el-dropdown-item icon="el-icon-view" @click.native="openFieldDrawer(scope.row)">查看字段
                            </el-dropdown-item>
                            <el-dropdown-item icon="el-icon-view" @click.native="openTemplateRuleDialog(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 :loading="syncDbLoading" icon="el-icon-upload" plain size="small" style="margin-left:6px;"
                   @click="syncDb"
        >
            一键导入正式库
        </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-if="false" 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-autocomplete v-model="fieldDialog.data.field" :fetch-suggestions="fetchSuggestions">
                    </el-autocomplete>
                </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" style="margin-left: 8px"
                               type="primary"
                               @click="queryFieldList"
                    >查询
                    </el-button>
                    <el-button type="success" @click="openFieldDialog">新增</el-button>
                    <el-button type="warning" @click="openQuicklyBind">快速绑定</el-button>
                    <el-button type="warning" @click="resetField" :loading="fieldDrawer.resetFieldLoading"
                               :disabled="!fieldDrawer.template.excelId"
                    >模板初始化
                    </el-button>
                    <el-button type="info" @click="createTable">物理表生成
                    </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"
            :loading="initTemplateDialog.loading"
        />
        <!-- 分析loading -->
        <AutoLoading
            :content="analyzeData.content"
            :loading="analyzeData.loading"
        />
        <!-- 模板规则 -->
        <el-dialog :visible.sync="templateRuleDialog.show" append-to-body close-on-click-modal title="模板规则"
                   width="80%"
        >
            <el-form size="small">
                <el-form-item>
                    <el-button icon="el-icon-plus" type="success" @click="openRuleAddDialog">添加</el-button>
                </el-form-item>
            </el-form>
            <el-table v-loading="templateRuleDialog.loading" :data="templateRuleDialog.ruleList"
                      border height="500px" max-height="500px" stripe
            >
                <el-table-column align="center" type="index" width="50"/>
                <el-table-column align="center" label="规则名称" prop="name" show-overflow-tooltip width="180"/>
                <el-table-column align="center" label="验证模式" prop="mode" show-overflow-tooltip width="120"
                />
                <el-table-column :formatter="contentFormat" align="center" label="验证内容" min-width="200" prop="content"
                                 show-overflow-tooltip
                />
                <el-table-column align="center" label="操作" width="120">
                    <template slot-scope="scope">
                        <el-button circle icon="el-icon-edit" plain
                                   size="small" type="primary" @click.stop="updateRuleByTemplate(scope.row)"
                        ></el-button>
                        <el-button circle icon="el-icon-delete" plain
                                   size="small" type="danger" @click.stop="deleteRuleByTemplate(scope.row)"
                        ></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
        <!--规则增改-->
        <el-dialog :close-on-click-modal="false" :title="ruleDialog.title" :visible.sync="ruleDialog.show"
                   append-to-body width="400px"
        >
            <el-form ref="ruleForm" :model="ruleDialog.data" label-width="80px">
                <el-form-item label="规则名称" prop="name" required>
                    <el-input v-model="ruleDialog.data.name" size="small"/>
                </el-form-item>
                <el-form-item label="验证模式" prop="mode" required>
                    <el-select v-model="ruleDialog.data.mode" size="small" style="width: 160px" @change="modeChange">
                        <el-option label="逻辑相加" value="逻辑相加"/>
                    </el-select>
                </el-form-item>
                <!--id1,id2=id1,id2-->
                <el-form-item prop="content">
                    <ArraySelect v-if="ruleDialog.data.mode === '逻辑相加'"
                                 v-model="ruleDialog.data.content"
                                 :data="templateRuleDialog.fieldList"
                    />
                </el-form-item>
                <el-form-item label="备注" prop="remarks">
                    <el-input v-model="ruleDialog.data.remarks" placeholder="备注" type="textarea"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitRule">确 定</el-button>
                <el-button @click="ruleDialog.show = false">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 机构字典 -->
        <el-dialog :visible.sync="orgDictDialog.show" append-to-body close-on-click-modal title="设置机构字典"
                   width="80%"
        >
            <el-form size="small">
                <el-form-item>
                    <el-button icon="el-icon-plus" type="success" @click="openAddOrgListDialog">添加</el-button>
                </el-form-item>
            </el-form>
            <el-table v-loading="orgDictDialog.loading" :data="orgDictDialog.orgList"
                      border height="500px" max-height="500px" stripe
            >
                <el-table-column align="center" type="index" width="50"/>
                <el-table-column align="center" label="标识" prop="value" show-overflow-tooltip/>
                <el-table-column align="center" label="机构类型" prop="orgType" show-overflow-tooltip/>
                <el-table-column align="center" label="机构名称" prop="label" show-overflow-tooltip/>
                <el-table-column align="center" label="机构地址" prop="address" show-overflow-tooltip/>
                <el-table-column align="center" label="行政区划代码" prop="unifiedCode" show-overflow-tooltip/>
                <el-table-column align="center" label="所属市" prop="city" show-overflow-tooltip/>
                <el-table-column align="center" label="所属区" prop="region" show-overflow-tooltip/>
                <el-table-column align="center" label="操作" width="120">
                    <template slot-scope="scope">
                        <el-button circle icon="el-icon-edit" plain
                                   size="small" type="primary" @click.stop="openUpdateOrgListDialog(scope.row)"
                        ></el-button>
                        <el-button circle icon="el-icon-delete" plain
                                   size="small" type="danger" @click.stop="deleteOrgList(scope.row)"
                        ></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
        <!--机构增改-->
        <el-dialog :close-on-click-modal="false" :title="orgListDialog.title" :visible.sync="orgListDialog.show"
                   append-to-body width="500px"
        >
            <el-form ref="orgListForm" :model="orgListDialog.data" label-width="100px">
                <el-form-item label="标识" prop="value" required>
                    <el-input v-model="orgListDialog.data.value" size="small"/>
                </el-form-item>
                <el-form-item label="机构类型" prop="orgType" required>
                    <el-input v-model="orgListDialog.data.orgType" size="small"/>
                </el-form-item>
                <el-form-item label="机构名称" prop="label" required>
                    <el-input v-model="orgListDialog.data.label" size="small"/>
                </el-form-item>
                <el-form-item label="机构地址" prop="address">
                    <el-input v-model="orgListDialog.data.address" size="small"/>
                </el-form-item>
                <el-form-item label="行政区划代码" prop="unifiedCode">
                    <el-input v-model="orgListDialog.data.unifiedCode" size="small"/>
                </el-form-item>
                <el-form-item label="所属市" prop="city">
                    <el-input v-model="orgListDialog.data.city" size="small"/>
                </el-form-item>
                <el-form-item label="所属区" prop="region">
                    <el-input v-model="orgListDialog.data.region" size="small"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitOrgList">确 定</el-button>
                <el-button @click="orgListDialog.show = false">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

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

export default {
    name: 'Emport',
    components: { ArraySelect, AutoLoading, 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: {},
                show: false,
                fieldList: [],
                queryForm: {
                    templateId: '',
                    code: '',
                    title: '',
                    coordinate: '',
                    field: '',
                    pageNum: 1,
                    pageSize: 10,
                    total: 0
                },
                queryFieldLoading: false,
                resetFieldLoading: false
            },
            quicklyBindDialog: { // 字段dialog
                show: false,
                ruleId: null,
                loading: false
            },
            initTemplateDialog: {
                template: null,
                show: false,
                loading: false
            },
            templateRuleDialog: { // 模板规则dialog
                template: null,
                ruleList: [],
                fieldList: [],
                show: false,
                loading: false
            },
            orgDictDialog: { // 机构字典弹出框
                loading: false,
                show: false,
                orgList: []
            },
            orgListDialog: { // 模板规则数据
                show: false,
                loading: false,
                title: '',
                data: {}
            },
            ruleDialog: { // 模板规则数据
                show: false,
                loading: false,
                title: '',
                data: {}
            },
            importLoading: false, // 导入数据loading
            queryTemplateLoading: false, // 模板查询loading
            queryTableLoading: false, // 查询数据表loading
            clearTempLoading: false, // 清空数据loading
            syncDbLoading: false, // 一键导入正式库loading
            templateList: [], // 模板列表
            analyzeData: {
                loading: false,
                content: ''
            }
        }
    },
    created() {
        this.queryTemplateLoading = true
        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.$refs.upload.clearFiles()
            this.queryForm.file = null
            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)
            let template = this.templateList.find(item => item.orgName === this.queryForm.orgName)
            formData.append('type', '1')
            formData.append('templateId', template.id)
            formData.append('year', template.year)
            formData.append('orgName', template.orgName)
            //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)
            this.initTemplateDialog.loading = true
            Emport.uploadExcel(formData).then(res => {
                if (res.code === 200) {
                    onSuccess()
                    this.$message.success('上传成功')
                    this.initTemplateDialog.show = false
                    this.initTemplate()
                }
            }).finally(_ => this.initTemplateDialog.loading = false)
        },
        // 重置字段信息
        resetField() {
            this.$confirm('此操作将覆盖原来设置的字段信息重新生成, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.fieldDrawer.resetFieldLoading = true
                Emport.resetField(this.fieldDrawer.template.excelId).then(res => {
                    if (res.code === 200) {
                        this.$message.success('字段初始化成功')
                        this.queryFieldList()
                    }
                }).finally(_ => this.fieldDrawer.resetFieldLoading = false)
            })
        },
        // 模板下载
        downloadTemplate(row) {
            Emport.downloadTemplate(row.excelId)
                .then(async res => {
                    const isFile = await Emport.blobValidate(res)
                    if (isFile) {
                        const { data } = await Emport.getTemplateFileName(row.excelId)
                        //const blob = new Blob([res])
                        saveAs(res, data.fileName)
                    }
                })
        },
        // 物理表生成
        createTable() {
            let template = this.fieldDrawer.template
            this.$prompt('请输入要生成的表名(表名会自动转成大写形式)', '物理表生成',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    beforeClose: (action, instance, done) => {
                        if (action === 'confirm') {
                            instance.confirmButtonLoading = true
                            Emport.createTable(instance.inputValue, template.id).then(res => {
                                if (res.code === 200) {
                                    this.$message.success({
                                        message: '物理表创建成功',
                                        duration: 1000 * 5
                                    })
                                    this.initTemplate()
                                    done()
                                }
                            }).finally(_ => instance.confirmButtonLoading = false)
                        } else {
                            done()
                        }
                    }
                }
            )
        },
        // 字段输入建议
        fetchSuggestions(qs, callback) {
            if (!this.fieldDict) {
                callback([])
                return
            }
            if (qs) {
                let result = this.fieldDict.filter(item => item.label.toUpperCase().includes(qs.toUpperCase()))
                callback(result)
            } else {
                callback(this.fieldDict)
            }
        },
        // 数据分析并导出
        analyzeExport() {
            let template = this.templateList.find(item => item.orgName === this.queryForm.orgName)
            if (!template || !this.queryForm.file || this.queryForm.file.status !== 'success') {
                this.$message.warning('请先导入数据文件')
                return
            }
            this.analyzeData.content = `正在分析 ${template.orgName} 数据...`
            this.analyzeData.loading = true
            Emport.analyzeExport(template.id)
                .then(res => {
                    saveAs(res, '分析结果.xlsx')
                }).finally(_ => this.analyzeData.loading = false)
        },
        // 清空数据
        clearTemp() {
            let template = this.templateList.find(item => item.orgName === this.queryForm.orgName)
            if (!template || !this.queryForm.file || this.queryForm.file.status !== 'success') {
                this.$message.warning('请先导入数据')
                return
            }
            this.clearTempLoading = true
            Emport.clearTemp(template).then(res => {
                if (res.code === 200) {
                    this.$message.success('清空成功')
                    this.initTemplate()
                }
            }).finally(_ => this.clearTempLoading = false)
        },
        // 一键导入正式库
        syncDb() {
            let template = this.templateList.find(item => item.orgName === this.queryForm.orgName)
            if (!template || !this.queryForm.file || this.queryForm.file.status !== 'success') {
                this.$message.warning('请先导入数据')
                return
            }
            this.syncDbLoading = true
            Emport.syncDb(template).then(res => {
                if (res.code === 200) {
                    this.$message.success('导入成功')
                    this.initTemplate()
                }
            }).finally(_ => this.syncDbLoading = false)
        },
        // 打开模板规则弹框
        openTemplateRuleDialog(row) {
            this.templateRuleDialog.template = { ...row }
            this.queryTemplateRule()
            this.templateRuleDialog.show = true
            Emport.getAllTemplateField(row.id).then(res => {
                this.templateRuleDialog.fieldList = res.data.map(item => {
                    return {
                        value: item.id,
                        label: StringUtil.mergeRule(item.code, item.title)
                    }
                })
            })

        },
        // 查询更新模板规则列表
        queryTemplateRule() {
            this.templateRuleDialog.loading = true
            Emport.getAllTemplateRule(this.templateRuleDialog.template.id).then(res => {
                this.templateRuleDialog.ruleList = res.data
            }).finally(_ => this.templateRuleDialog.loading = false)
        },
        // 验证模式修改触发事件
        modeChange(value) {
            this.$set(this.ruleDialog.data, 'content', '')
        },
        // 提交规则
        submitRule() {
            this.$refs.ruleForm.validate(validate => {
                if (validate) {
                    if (this.ruleDialog.title === '新增规则') {
                        Emport.addRuleByTemplate({
                            ...this.ruleDialog.data,
                            tid: this.templateRuleDialog.template.id
                        }).then(res => {
                            this.ruleDialog.show = false
                            this.queryTemplateRule()
                        })
                    } else {
                        Emport.updateRuleByTemplate(this.ruleDialog.data).then(res => {
                            this.ruleDialog.show = false
                            this.queryTemplateRule()
                        })
                    }
                }
            })
        },
        // 打开规则新增框框
        openRuleAddDialog() {
            this.ruleDialog.data = {
                type: '模板规则'
            }
            this.ruleDialog.title = '新增规则'
            this.ruleDialog.show = true
        },
        // 打开规则修改弹框
        updateRuleByTemplate(row) {
            this.ruleDialog.data = { ...row }
            this.ruleDialog.title = '修改规则'
            this.ruleDialog.show = true
        },
        // 验证模式格式化
        modeFormat(row) {
            if (row.mode === '1') {
                return '逻辑相加'
            }
            return ''
        },
        // 规则配置格式化
        contentFormat(row) {
            if (row.content) {
                let split = row.content.split('=')
                let arr1 = split[0].split(',')
                let arr2 = split[1].split(',')
                return arr1.map(item => {
                    let data = this.templateRuleDialog.fieldList.find(i => i.value === item)
                    if (data) {
                        return data.label
                    } else {
                        return item
                    }
                }).join('+') + '=' + arr2.map(item => {
                    let data = this.templateRuleDialog.fieldList.find(i => i.value === item)
                    if (data) {
                        return data.label
                    } else {
                        return item
                    }
                })
            }
        },
        // 删除模板规则
        deleteRuleByTemplate(row) {
            this.$confirm(`是否删除规则 ${row.name} ?`, '删除',
                {
                    type: 'warning',
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    beforeClose: (action, instance, done) => {
                        if (action === 'confirm') {
                            Emport.deleteRuleByTemplate(row.id, this.templateRuleDialog.template.id).then(res => {
                                done()
                                this.queryTemplateRule()
                            })
                        } else {
                            done()
                        }
                    }
                }
            )
        },
        // 打开机构字典列表
        openOrgDictDialog() {
            this.initOrgList()
            this.orgDictDialog.show = true
        },
        openAddOrgListDialog() {
            this.orgListDialog.title = '新增机构'
            this.orgListDialog.data = {}
            this.orgListDialog.show = true
        },
        openUpdateOrgListDialog(row) {
            this.orgListDialog.title = '修改机构'
            this.orgListDialog.data = { ...row }
            this.orgListDialog.show = true
        },
        deleteOrgList(row) {
            this.$confirm(`是否删除机构 ${row.label}`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                Emport.deleteDict(row.id).then(res => {
                    if (res.code === 200) {
                        this.$message.success('删除成功')
                        this.initOrgList()
                    }
                })
            })
        },
        // 初始化机构列表
        initOrgList() {
            this.orgDictDialog.loading = true
            Emport.queryDict('orgList').then(res => {
                if (res.code === 200) {
                    this.orgDictDialog.orgList = res.data
                }
            }).finally(_ => this.orgDictDialog.loading = false)
        },
        // 提交机构字典信息
        submitOrgList() {
            this.$refs.orgListForm.validate(valid => {
                if (valid) {
                    let data = {
                        id: this.orgListDialog.data.id,
                        type: 'orgList',
                        label: this.orgListDialog.data.label,
                        value: this.orgListDialog.data.value,
                        remarks: JSON.stringify({
                            orgType: this.orgListDialog.data.orgType,
                            address: this.orgListDialog.data.address,
                            unifiedCode: this.orgListDialog.data.unifiedCode,
                            city: this.orgListDialog.data.city,
                            region: this.orgListDialog.data.region
                        })
                    }
                    if (this.orgListDialog.title === '新增机构') {
                        Emport.addDict(data)
                            .then(res => {
                                this.orgListDialog.show = false
                                this.initOrgList()
                            })
                    } else {
                        Emport.updateDict(data)
                            .then(res => {
                                this.orgListDialog.show = false
                                this.initOrgList()
                            })
                    }
                }
            })
        }
    }
}
</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>
