<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-set-up" plain size="small" @click="openOrgDictDialog">设置机构字典</el-button>
                <el-button icon="el-icon-pie-chart" plain
                           size="small"
                           style="margin-left:6px;" @click="analyzeExport"
                >分析并导出
                </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="yearFormat" align="center" label="数据年份" prop="year" show-overflow-tooltip/>
            <el-table-column :formatter="templateStatusFormat" align="center" label="模板状态" show-overflow-tooltip/>
            <el-table-column :formatter="dataStatusFormat" align="center" label="数据状态" prop="dataStatus"
                             show-overflow-tooltip
            />
            <el-table-column :formatter="importStatusFormat" align="center" label="正式库导入状态" prop="importStatus"
                             show-overflow-tooltip
            />
            <el-table-column align="center" label="导入时间" prop="importTime" 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="openTemplateErrorDialog(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="value" label="年份">
                    <el-date-picker
                        format="yyyy" value-format="yyyy"
                        v-model="yearDialog.data.value"
                        type="year"
                    >
                    </el-date-picker>
                </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" filterable clearable>
                        <el-option v-for="item in metaFieldDict" :key="item.value" :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="95%" :title="fieldDrawer.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="clearPageToSearch"
                    >查询
                    </el-button>
                    <el-button type="success" @click="openFieldDialog">新增</el-button>
                    <el-button type="warning" @click="openQuicklyBind">快速绑定</el-button>
                    <el-button :disabled="!fieldDrawer.template.excelId" type="warning"
                               @click="openSwitchYear('template')"
                    >模板初始化
                    </el-button>
                    <el-button type="warning" @click="openSwitchYear('rule')">规则同步</el-button>
                    <el-button type="info" @click="createTable">物理表生成
                    </el-button>
                    <el-button type="info" @click="querySyncField">字段同步
                    </el-button>
                    <el-button type="info" @click="sameFieldCheck">相同字段检查
                    </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 width="120"/>
                <el-table-column align="center" label="指标名称" min-width="200" prop="title" show-overflow-tooltip/>
                <el-table-column align="center" label="旧指标" min-width="300">
                    <template slot-scope="scope">
                        <el-select :value="scope.row.oldId" clearable filterable style="width: 100%"
                                   @change="value=>changeFieldSelect(scope.row,value)"
                        >
                            <el-option v-for="item in fieldDrawer.fieldDict" :key="item.id" :label="item.label"
                                       :value="item.id"
                            />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="字段名" min-width="260" prop="fieldName"
                                 show-overflow-tooltip
                />
                <el-table-column align="center" label="字段注释" min-width="150" prop="fieldComment"
                                 show-overflow-tooltip
                />
                <el-table-column align="center" label="数据坐标" prop="coordinate" show-overflow-tooltip width="100"/>
                <el-table-column align="center" label="计量单位" prop="unit" show-overflow-tooltip width="90"/>
                <el-table-column align="center" fixed="right" 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="templateErrorDialog.show"
                   append-to-body
                   close-on-click-modal
                   title="错误字段查询"
                   width="80%"
        >
            <div style="width: 100%">
                <el-form size="small">
                    <el-form-item>
                        <el-button icon="el-icon-plus" type="success" :disabled="templateErrorDialog.multiple" v-on:click="handleErrorFieldSync">同步
                        </el-button>
                    </el-form-item>
                </el-form>
                <el-table ref="errorFieldTable"
                          v-loading="templateErrorDialog.loading"
                          :data="templateErrorDialog.errorFieldList"
                          @select="selectErrorField"
                          @selection-change="handleErrorFieldSelectionChange"
                          border height="500px" max-height="500px" width="1000" stripe style="width: 100%"
                >
                    <el-table-column type="selection" min-width="55" :selectable="errorFieldSelectable"/>
                    <el-table-column align="center" label="字段标题" prop="title" show-overflow-tooltip
                                     min-width="200"
                    />
                    <el-table-column align="center" label="元字段名" prop="fieldName" show-overflow-tooltip
                                     min-width="230"
                    />
                    <el-table-column align="center" label="元字段类型" prop="fieldType" show-overflow-tooltip
                                     min-width="150"
                    />
                    <el-table-column align="center" label="物理表字段类型" prop="columnType" show-overflow-tooltip
                                     min-width="150"
                    />
                    <el-table-column align="center" label="物理表名" prop="tableName" show-overflow-tooltip
                                     min-width="230"
                    />
                    <el-table-column align="center" label="提示" prop="tip" show-overflow-tooltip  min-width="320"/>
                </el-table>
            </div>
        </el-dialog>
        <!-- 模板规则 -->
        <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="1-精确到小数点后一位"/>
                </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="90%"
        >
            <el-form inline size="small">
                <el-form-item>
                    <el-button v-if="false" icon="el-icon-plus" type="success" @click="openAddOrgListDialog">添加
                    </el-button>
                    <el-button :loading="orgDictDialog.loading" icon="el-icon-plus" type="success" @click="exportExcel">
                        导出
                    </el-button>
                </el-form-item>
                <el-form-item label="查询全部">
                    <el-switch
                        v-model="orgDictDialog.type"
                        active-color="#13ce66"
                        active-value="1"
                        inactive-value="0"
                        @change="typeChange"
                    >
                    </el-switch>
                </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="ROWCODE" show-overflow-tooltip/>
                <el-table-column align="center" label="机构类型" prop="ORG_TYPE" show-overflow-tooltip/>
                <el-table-column align="center" label="机构名称" prop="ORG_NAME" show-overflow-tooltip/>
                <el-table-column align="center" label="机构地址" prop="MAILING_ADDRESS" show-overflow-tooltip/>
                <el-table-column align="center" label="所属区县" prop="DWSSQX" show-overflow-tooltip/>
                <el-table-column align="center" label="行政区划代码" prop="AREA_NUMBER_CODE" show-overflow-tooltip/>
                <el-table-column v-if="false" align="center" label="所属市" prop="CITY" show-overflow-tooltip/>
                <el-table-column :formatter="AREAFormatter" align="center" label="对应区名称" prop="AREA"
                                 show-overflow-tooltip
                />
                <el-table-column align="center" label="操作" width="80">
                    <template slot-scope="scope">
                        <el-button circle icon="el-icon-edit" plain
                                   size="small" type="primary" @click.stop="openUpdateOrgListDialog(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="ROWCODE" required>
                    <el-input v-model="orgListDialog.data.ROWCODE" disabled size="small"/>
                </el-form-item>
                <el-form-item label="机构类型" prop="ORG_TYPE">
                    <el-input v-model="orgListDialog.data.ORG_TYPE" disabled size="small"/>
                </el-form-item>
                <el-form-item label="机构名称" prop="ORG_NAME" required>
                    <el-input v-model="orgListDialog.data.ORG_NAME" size="small"/>
                </el-form-item>
                <el-form-item label="机构地址" prop="MAILING_ADDRESS">
                    <el-input v-model="orgListDialog.data.MAILING_ADDRESS" autosize size="small" type="textarea"/>
                </el-form-item>
                <el-form-item label="行政区划代码" prop="AREA_NUMBER_CODE">
                    <!--                    <el-input v-model="orgListDialog.data.AREA_NUMBER_CODE" size="small"/>-->
                    <el-autocomplete v-model="orgListDialog.data.AREA_NUMBER_CODE"
                                     :fetch-suggestions="areaSearch"
                                     size="small"
                    >
                        <template slot-scope="{ item }">
                            {{ item.suggestion }}
                        </template>
                    </el-autocomplete>
                </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>
        <!--选择初始化年份-->
        <el-dialog title="请选择同步年份" :visible.sync="otherYearDialog.show"
                   append-to-body width="300px" v-loading="otherYearDialog.loading"
        >
            <el-select v-model="otherYearDialog.year">
                <el-option v-for="item in otherYearDialog.list" :key="item" :value="item" :label="item"></el-option>
            </el-select>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitOtherYear">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 字段同步 -->
        <el-dialog :visible.sync="syncFieldDialog.show" append-to-body close-on-click-modal title="字段同步"
                   width="80%"
        >
            <el-form size="small">
                <el-form-item>
                    <el-button :loading="syncFieldDialog.loading" icon="el-icon-plus" type="success" @click="syncField">
                        同步新增数据库字段
                    </el-button>
                </el-form-item>
            </el-form>
            <el-table v-loading="syncFieldDialog.loading" :data="syncFieldDialog.list"
                      border height="500px" max-height="500px" stripe @selection-change="handleSelectionChange"
            >
                <el-table-column align="center" type="selection" width="50"/>
                <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="fieldName" show-overflow-tooltip/>
                <el-table-column align="center" label="字段类型" prop="fieldType" show-overflow-tooltip/>
            </el-table>
        </el-dialog>
        <!-- 相同字段 -->
        <el-dialog :visible.sync="sameFieldDialog.show" append-to-body close-on-click-modal title="相同字段整理"
                   width="80%"
        >
            <el-table :data="sameFieldDialog.list"
                      border height="500px" max-height="500px" stripe
            >
                <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="fieldName" show-overflow-tooltip/>
                <el-table-column align="center" label="字段类型" prop="fieldType" show-overflow-tooltip/>
                <el-table-column align="center" label="字段备注" prop="fieldComment" show-overflow-tooltip/>
            </el-table>
        </el-dialog>
        <!-- 错误列表 -->
        <el-dialog :visible.sync="errorDialog.show" append-to-body close-on-click-modal title="异常列表"
                   width="60%"
        >
            <el-table
                :data="errorDialog.data"
                style="width: 100%"
            >
                <el-table-column
                    prop="error"
                    label="错误信息"
                >
                </el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>

<script>
import * as DataField from '@/api/emport/DataField'
import * as DataImport from '@/api/emport/DataImport'
import * as DataRule from '@/api/emport/DataRule'
import * as DataTemplate from '@/api/emport/DataTemplate'
import * as DictData from '@/api/emport/DictData'
import * as ExcelData from '@/api/emport/ExcelData'
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'
import { syncTemplateErrorField } from '@/api/emport/DataTemplate'

export default {
    name: 'Emport',
    computed: {
        StringUtil() {
            return StringUtil
        }
    },
    components: { ArraySelect, AutoLoading, AutoUpload },
    data() {
        return {
            // 页面查询字段
            queryForm: {
                year: '',
                orgName: '', //数据类型
                file: null
            },
            yearDict: [], // 年份字典
            orgDict: [], // 机构类型字典
            ruleDict: [], // 规则字典
            dataSourceList: [], // 数据源列表
            tableList: [], // 表列表
            fieldDict: [], // 字段字典
            metaFieldDict: [], //
            errorDialog: {  // 错误列表dialog
                show: false,
                data: []
            },
            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: { // 字段抽屉
                title: '字段信息',
                template: {},
                show: false,
                fieldList: [],
                queryForm: {
                    templateId: '',
                    code: '',
                    title: '',
                    coordinate: '',
                    field: '',
                    pageNum: 1,
                    pageSize: 10,
                    total: 0
                },
                queryFieldLoading: false,
                fieldDict: [] // 匹配上个模板的字段字典
            },
            quicklyBindDialog: { // 字段dialog
                show: false,
                ruleId: null,
                loading: false
            },
            initTemplateDialog: {
                template: null,
                show: false,
                loading: false
            },
            templateErrorDialog: {// 错误字段查询dialog
                template: null,
                errorFieldList: [],
                selectErrorFieldList: [],
                show: false,
                loading: false,
                multiple: true
            },
            templateRuleDialog: { // 模板规则dialog
                template: null,
                ruleList: [],
                fieldList: [],
                show: false,
                loading: false
            },
            orgDictDialog: { // 机构字典弹出框
                loading: false,
                show: false,
                orgList: [],
                areaDict: [],
                type: '0'
            },
            orgListDialog: { // 模板规则数据
                show: false,
                loading: false,
                title: '',
                data: {}
            },
            ruleDialog: { // 模板规则数据
                show: false,
                loading: false,
                title: '',
                data: {}
            },
            otherYearDialog: { // 模板重置选择年份数据
                year: '',
                show: false,
                loading: false,
                list: [],
                type: ''
            },
            syncFieldDialog: {  // 字段同步
                show: false,
                loading: false,
                list: [],
                checked: []
            },
            sameFieldDialog: { // 相同字段列表
                show: false,
                list: []
            },
            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()
        this.initMetaFieldDict()
    },
    methods: {
        // 初始化年份字典
        initYearDict(callback) {
            DictData.queryDict('year').then((res) => {
                if (res.code === 200) {
                    this.yearDict = res.data
                    if (callback) callback(res.data)
                }
            })
        },
        // 初始化机构类型字典
        initOrgDict(callback) {
            DictData.queryDict('org').then((res) => {
                if (res.code === 200) {
                    this.orgDict = res.data
                    if (callback) callback(res.data)
                }
            })
        },
        // 初始化数据源字典
        initDataSource() {
            DataImport.queryDatasource().then(res => {
                if (res.code === 200) {
                    this.dataSourceList = res.data.map(item => {
                        return {
                            label: item.datasourceName,
                            value: item.datasourceName,
                            id: item.datasourceId
                        }
                    })
                }
            })
        },
        // 初始化规则字典
        initRuleDict() {
            DataRule.queryRuleDict().then(res => {
                this.ruleDict = res.data.map(item => {
                    return {
                        value: item.id,
                        label: item.name
                    }
                })
            })
        },
        // 初始化元字段字典
        initMetaFieldDict() {
            DataField.getMetaFieldDict().then(res => {
                this.metaFieldDict = res.data.map(item => {
                    return {
                        value: item.id,
                        label: StringUtil.mergeStr(item.fieldName, item.fieldComment)
                    }
                })
            })
        },
        // 初始化数据表列表
        initTable(datasourceId, callback) {
            this.queryTableLoading = true
            DataImport.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() {
            DataField.queryFieldDict({ templateId: this.fieldDrawer.template.id }).then(res => {
                this.fieldDrawer.fieldDict = res.data.map(item => {
                    return {
                        id: item.id,
                        label: StringUtil.merge('  ', item.code, item.title),
                        field: item.field
                    }
                })
            })
        },
        // 初始化模板列表
        initTemplate() {
            this.$refs.upload.clearFiles()
            this.queryForm.file = null
            this.queryTemplateLoading = true
            DataTemplate.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 === '新增年份') {
                        DictData.addDict({
                            ...this.yearDialog.data,
                            label: this.yearDialog.data.value + '年'
                        })
                            .then(res => {
                                this.yearDialog.show = false
                                this.initYearDict()
                            })
                    } else {
                        DictData.updateDict({
                            ...this.yearDialog.data,
                            label: this.yearDialog.data.value + '年'
                        })
                            .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') {
                            DictData.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 === '新增机构类型') {
                        DictData.addDict({
                            ...this.orgDialog.data,
                            label: this.orgDialog.data.value
                        })
                            .then(res => {
                                this.orgDialog.show = false
                                this.initOrgDict()
                            })
                    } else {
                        DictData.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') {
                            DictData.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);
            ExcelData.uploadExcel(formData)
                .then((res) => {
                    if (res.code === 200) {
                        if (res.data && res.data.length > 0) {
                            onError()
                            // 弹出数据导入异常
                            this.errorDialog = {
                                show: true,
                                data: res.data.map(item => {
                                    return { error: item }
                                })
                            }
                        } else {
                            onSuccess()
                        }
                    } else {
                        onError()
                    }
                })
                .finally((_) => {
                    this.importLoading = false
                })
        },
        // 触发导入
        triggerImport() {
            if (this.queryForm.file) {
                let template = this.templateList.find(item => item.orgName === this.queryForm.orgName)
                if (template) {
                    this.$refs.upload.submit()
                } else {
                    this.$message.warning('没有此类型的模板,请选择其它的数据类型')
                }

            } 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 === '添加模板') {
                        DataTemplate.addTemplate(this.templateDialog.data)
                            .then(res => {
                                this.templateDialog.show = false
                                this.initTemplate()
                            })
                    } else {
                        DataTemplate.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') {
                            DataTemplate.deleteTemplate(row.id).then(res => {
                                done()
                                this.initTemplate()
                            })
                        } else {
                            done()
                        }
                    }
                }
            )
        },
        // 提交字段dialog
        submitField() {
            this.$refs.fieldForm.validate(valid => {
                if (valid) {
                    if (this.fieldDialog.title === '新增字段') {
                        DataField.addField(this.fieldDialog.data)
                            .then(res => {
                                this.fieldDialog.show = false
                                this.queryFieldList()
                            })
                    } else {
                        DataField.updateField(this.fieldDialog.data)
                            .then(res => {
                                this.fieldDialog.show = false
                                this.queryFieldList()
                            })
                    }
                }
            })
        },
        // 字段匹配选择
        changeFieldSelect(row, id) {
            this.fieldDrawer.queryFieldLoading = true
            let data = {
                id: row.id,
                field: ''
            }
            if (id) {
                let temp = this.fieldDrawer.fieldDict.find(item => item.id === id)
                if (temp) {
                    data.field = temp.field
                }
            }
            DataField.updateField(data)
                .then(res => {
                    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.fieldDrawer.title = `${row.year}${row.orgName}-字段信息`
            this.initFieldDict()
            this.queryFieldList()
        },
        // 重置分页再查询字段列表
        clearPageToSearch() {
            this.fieldDrawer.queryForm.total = 0
            this.fieldDrawer.queryForm.pageNum = 1
            this.queryFieldList()
        },
        // 查询字段列表
        queryFieldList() {
            this.fieldDrawer.queryFieldLoading = true
            DataField.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') {
                            DataField.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
                DataRule.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
            DataRule.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
            DataRule.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 '未上传'
            }
        },
        dataStatusFormat(row) {
            if (row.dataStatus) {
                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
            ExcelData.uploadExcel(formData).then(res => {
                if (res.code === 200) {
                    onSuccess()
                    this.$message.success('上传成功')
                    this.initTemplateDialog.show = false
                    this.initTemplate()
                }
            }).finally(_ => this.initTemplateDialog.loading = false)
        },
        // 打开年份选择框
        openSwitchYear(type) {
            this.otherYearDialog.show = true
            this.otherYearDialog.type = type
            this.otherYearDialog.year = null
            DataTemplate.queryOtherYears(this.fieldDrawer.template)
                .then(res => {
                    this.otherYearDialog.list = res.data
                })
        },
        // 提交同步年份信息
        submitOtherYear() {
            if (this.otherYearDialog.type === 'template') {
                this.otherYearDialog.loading = true
                DataField.resetField(this.fieldDrawer.template.excelId,
                    this.otherYearDialog.year).then(res => {
                    if (res.code === 200) {
                        this.$message.success('字段初始化成功')
                        this.otherYearDialog.show = false
                        this.queryFieldList()
                    }
                }).finally(_ => this.otherYearDialog.loading = false)
            } else {
                if (this.otherYearDialog.year) {
                    this.otherYearDialog.loading = true
                    DataRule.syncRuleByYear(this.fieldDrawer.template.id, this.otherYearDialog.year).then(res => {
                        if (res.code === 200) {
                            this.$message.success('规则同步成功')
                            this.otherYearDialog.show = false
                            this.queryFieldList()
                        }
                    }).finally(_ => this.otherYearDialog.loading = false)
                }
            }
        },
        // 模板下载
        downloadTemplate(row) {
            ExcelData.downloadTemplate(row.excelId)
                .then(async res => {
                    const isFile = await ExcelData.blobValidate(res)
                    if (isFile) {
                        const { data } = await ExcelData.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
                            DataImport.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
            DataImport.analyzeExport(template.id)
                .then(res => {
                    saveAs(res, '分析结果.zip')
                }).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
            DataImport.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
            DataImport.syncDb(template).then(res => {
                if (res.code === 200) {
                    this.$message.success('导入成功')
                    this.initTemplate()
                }
            }).finally(_ => this.syncDbLoading = false)
        },
        getErrorFieldList(row) {
            this.templateErrorDialog.loading = true
            DataTemplate.getTemplateErrorField(row.id).then(res => {
                this.templateErrorDialog.errorFieldList = res.data
                this.templateErrorDialog.loading = false
            })
        },
        // 异常字段查询弹窗
        openTemplateErrorDialog(row) {
            this.templateErrorDialog.template = { ...row }
            this.templateErrorDialog.show = true
            this.getErrorFieldList(row)
        },
        handleErrorFieldSelectionChange(selection) {
            this.templateErrorDialog.selectErrorFieldList = selection
            this.templateErrorDialog.multiple = !selection.length
        },
        selectErrorField(selection, row) {
            //校验数据类型
            let fieldType = row.fieldType.substring(0, row.fieldType.indexOf('('))
            let columnType = row.columnType.substring(0, row.columnType.indexOf('('))

            //校验长度
            if (row.fieldType.search('NUMBER') !== -1 && columnType.search('VARCHAR') !== -1) {
                let fieldPrecision =  row.fieldType.substring(row.fieldType.indexOf('(') + 1, row.fieldType.indexOf(','))
                let fieldScale =  row.fieldType.substring(row.fieldType.indexOf(',') + 1, row.fieldType.indexOf(')'))
                let columnPrecision =  row.columnType.substring(row.columnType.indexOf('(') + 1, row.columnType.indexOf(','))
                let columnScale =  row.columnType.substring(row.columnType.indexOf(',') + 1, row.columnType.indexOf(')'))
                if (Number(fieldPrecision) < Number(columnPrecision)) this.$message.warning('字段长度减小可能会造成数据丢失!')
                if (Number(fieldScale) < Number(columnScale)) this.$message.warning('字段精度减小可能会造成数据丢失!')
                return
            } else if (fieldType.search('VARCHAR') !== -1 && columnType.search('VARCHAR') !== -1) {
                let fieldLength =  row.fieldType.substring(row.fieldType.indexOf('(') + 1, row.fieldType.indexOf(')'))
                let columnLength =  row.columnType.substring(row.columnType.indexOf('(') + 1, row.columnType.indexOf(')'))
                if (Number('fieldLength') < Number('columnLength') )  this.$message.warning('长度减小可能会造成数据丢失!')
                return
            }

            if (fieldType !== columnType) this.$message.warning('字段类型不相同，强行同步可能会造成数据丢失!')
        },
        errorFieldSelectable(row, rowIndex) {
            let flag = false
            let fieldType = row.fieldType.substring(0, row.fieldType.indexOf('('))
            let columnType = row.columnType.substring(0, row.columnType.indexOf('('))
            if (fieldType !== columnType) row.tip ='字段类型不相同，强行同步可能会造成数据丢失!'
            if (fieldType === columnType) {
                flag = true
            } else if (fieldType.search('VARCHAR') !== -1 && columnType.search('VARCHAR') !== -1) {
                row.tip = ''
                flag = true
                let fieldLength =  row.fieldType.substring(row.fieldType.indexOf('(') + 1, row.fieldType.indexOf(')'))
                let columnLength =  row.columnType.substring(row.columnType.indexOf('(') + 1, row.columnType.indexOf(')'))
                if (Number('columnLength') > Number('fieldLength'))  row.tip ='长度减小可能会造成数据丢失!'
            }
            if (fieldType.search('NUMBER') !== -1 && columnType.search('NUMBER') !== -1) {
                let fieldPrecision =  row.fieldType.substring(row.fieldType.indexOf('(') + 1, row.fieldType.indexOf(','))
                let fieldScale =  row.fieldType.substring(row.fieldType.indexOf(',') + 1, row.fieldType.indexOf(')'))
                let columnPrecision =  row.columnType.substring(row.columnType.indexOf('(') + 1, row.columnType.indexOf(','))
                let columnScale =  row.columnType.substring(row.columnType.indexOf(',') + 1, row.columnType.indexOf(')'))
                if (Number(fieldPrecision) < Number(columnPrecision)) row.tip = '字段长度减小可能会造成数据丢失!'
                if (Number(fieldScale) < Number(columnScale)) row.tip = '字段精度减小可能会造成数据丢失!'
            }
            return flag
        },
        handleErrorFieldSync() {
            console.log('selection',this.templateErrorDialog.selectErrorFieldList)
            DataTemplate.syncTemplateErrorField(this.templateErrorDialog.selectErrorFieldList).then(res => {
                this.getErrorFieldList(this.templateErrorDialog.template)
                this.$message.success('同步成功')
            })
        },
        // 打开模板规则弹框
        openTemplateRuleDialog(row) {
            this.templateRuleDialog.template = { ...row }
            this.queryTemplateRule()
            this.templateRuleDialog.show = true
            DataTemplate.getAllTemplateField(row.id).then(res => {
                console.log('模板规则查询', res)
                this.templateRuleDialog.fieldList = res.data.map(item => {
                    return {
                        value: item.field,
                        label: StringUtil.mergeRule(item.code, item.title)
                    }
                })
            })

        },
        // 查询更新模板规则列表
        queryTemplateRule() {
            this.templateRuleDialog.loading = true
            DataTemplate.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 === '新增规则') {
                        DataTemplate.addRuleByTemplate({
                            ...this.ruleDialog.data,
                            tid: this.templateRuleDialog.template.id
                        }).then(res => {
                            this.ruleDialog.show = false
                            this.queryTemplateRule()
                        })
                    } else {
                        DataTemplate.updateRuleByTemplate(this.ruleDialog.data).then(res => {
                            this.ruleDialog.show = false
                            this.queryTemplateRule()
                        })
                    }
                }
            })
        },
        // 打开规则新增框框
        openRuleAddDialog() {
            this.ruleDialog.data = {
                type: '模板规则',
                remarks: '0'
            }
            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
                    }
                }).join('+')
            }
        },
        // 删除模板规则
        deleteRuleByTemplate(row) {
            this.$confirm(`是否删除规则 ${row.name} ?`, '删除',
                {
                    type: 'warning',
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    beforeClose: (action, instance, done) => {
                        if (action === 'confirm') {
                            DataTemplate.deleteRuleByTemplate(row.id, this.templateRuleDialog.template.id).then(res => {
                                done()
                                this.queryTemplateRule()
                            })
                        } else {
                            done()
                        }
                    }
                }
            )
        },
        // 打开机构字典列表
        openOrgDictDialog() {
            //this.initOrgList()
            this.orgDictDialog.show = true
            this.orgDictDialog.loading = true
            this.orgDictDialog.type = '0'
            // 查询机构字典
            DictData.queryDict('area').then(res => {
                this.orgDictDialog.areaDict = res.data.map(item => {
                    return {
                        ...item,
                        suggestion: StringUtil.mergeStr(item.label, item.value)
                    }
                })
                ExcelData.queryArea(this.queryForm.orgName, this.queryForm.year, this.orgDictDialog.type).then(res => {
                    if (res.code === 200) {
                        this.orgDictDialog.orgList = res.data.map(item => {
                            if (item.AREA_NUMBER_CODE) {
                                let temp = this.orgDictDialog.areaDict.find(area => area.value === item.AREA_NUMBER_CODE)
                                if (temp) {
                                    item.AREA = temp.label
                                }
                            }
                            return item
                        })
                    }
                }).finally(_ => this.orgDictDialog.loading = false)
            })
        },
        typeChange() {
            this.orgDictDialog.loading = true
            ExcelData.queryArea(this.queryForm.orgName, this.queryForm.year, this.orgDictDialog.type).then(res => {
                if (res.code === 200) {
                    this.orgDictDialog.orgList = res.data
                }
            }).finally(_ => this.orgDictDialog.loading = false)
        },
        AREAFormatter(row) {
            if (row.AREA_NUMBER_CODE) {
                let temp = this.orgDictDialog.areaDict.find(area => area.value === row.AREA_NUMBER_CODE)
                return temp ? temp.label : ''
            }
            return ''
        },
        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(() => {
                DictData.deleteDict(row.id).then(res => {
                    if (res.code === 200) {
                        this.$message.success('删除成功')
                        this.initOrgList()
                    }
                })
            })
        },
        // 初始化机构列表
        initOrgList() {
            this.orgDictDialog.loading = true
            DictData.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 === '新增机构') {
                        DictData.addDict(data)
                            .then(res => {
                                this.orgListDialog.show = false
                                this.initOrgList()
                            })
                    } else {
                        DictData.updateDict(data)
                            .then(res => {
                                this.orgListDialog.show = false
                                this.initOrgList()
                            })
                    } */
                    ExcelData.updateArea({
                        ...this.orgListDialog.data,
                        name: this.queryForm.orgName,
                        year: this.queryForm.year
                    })
                        .then(res => {
                            this.orgListDialog.show = false
                            this.orgDictDialog.loading = true
                            // 查询机构字典
                            ExcelData.queryArea(this.queryForm.orgName, this.queryForm.year).then(res => {
                                if (res.code === 200) {
                                    this.orgDictDialog.orgList = res.data.map(item => {
                                        if (item.AREA_NUMBER_CODE) {
                                            let temp = this.orgDictDialog.areaDict.find(area => area.value === item.AREA_NUMBER_CODE)
                                            if (temp) {
                                                item.AREA = temp.label
                                            }
                                        }
                                        return item
                                    })
                                }
                            }).finally(_ => this.orgDictDialog.loading = false)
                        })
                }
            })
        },
        // 导出修改后的excel
        exportExcel() {
            this.orgDictDialog.loading = true
            ExcelData.exportExcel(this.queryForm.orgName, this.queryForm.year).then(async res => {
                const isFile = await ExcelData.blobValidate(res)
                if (isFile) {
                    saveAs(res, this.queryForm.orgName + this.queryForm.year + '年.xlsx')
                }
            }).finally(_ => this.orgDictDialog.loading = false)
        },
        // 字段同步
        querySyncField() {
            this.syncFieldDialog.show = true
            this.syncFieldDialog.loading = true
            this.syncFieldDialog.checked = []
            DataField.querySyncField(this.fieldDrawer.template.id).then(res => {
                this.syncFieldDialog.list = res.data
            }).finally(_ => this.syncFieldDialog.loading = false)
        },
        syncField() {
            if (this.syncFieldDialog.checked && this.syncFieldDialog.checked.length > 0) {
                this.syncFieldDialog.loading = true
                DataField.syncField(this.syncFieldDialog.checked).then(res => {
                    if (res.code === 200) {
                        this.$message.success('新增字段成功')
                        this.syncFieldDialog.show = false
                    }
                }).finally(_ => this.syncFieldDialog.loading = false)
            }
        },
        handleSelectionChange(val) {
            this.syncFieldDialog.checked = val
        },
        areaSearch(qs, callback) {
            if (!this.orgDictDialog.areaDict) {
                callback([])
                return
            }
            if (qs) {
                //
                let result = this.orgDictDialog.areaDict.filter(item => {
                    return item.suggestion.includes(qs)
                })
                callback(result)
            } else {
                callback(this.orgDictDialog.areaDict)
            }
        },
        sameFieldCheck() {
            let templateId = this.fieldDrawer.template.id
            DataField.sameFieldCheck(templateId).then(res => {
                if (!res.data || res.data.length === 0) {
                    this.$message.success('无重复字段,可建表')
                } else {
                    this.sameFieldDialog.list = res.data
                    this.sameFieldDialog.show = true
                }
            })
        }
    }
}
</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>
