<template>
    <div class="organizManage-main data-permission-add">
        <div
            class="organizManage-mainLeft"
            ref="mainLeft"
            :style="{height: leftHeight + 'px'}"
        >
            <div class="public-function-div">数据字段列表</div>
            <div class="post-m">
                <el-row>
                    <el-col :span="18">
                        <el-form
                            class="userModal"
                        >
                            <el-row>
                                <!-- <el-col :span="12">
                  <el-form-item label="数据源">
                    <el-input placeholder="请输入" size="small"></el-input>
                  </el-form-item>
                </el-col> -->
                                <el-col :span="20">
                                    <el-form-item style="width:50%; display:inline-block">
                                        <el-select
                                            v-model="fieldTable.tableParams.form.tableName"
                                            v-if="operate === 'edit'"
                                            disabled="disabled"
                                            placeholder="表名"
                                            style="width: 100%;"
                                            size="small"
                                            @change="tableList = [...tableList]"
                                        >
                                            <el-option
                                                v-for="(item, index) in tableList"
                                                :key="index"
                                                :label="item.tableCnName"
                                                :value="item.tableName"
                                            ></el-option>
                                        </el-select>
                                        <el-select
                                            v-model="fieldTable.tableParams.form.tableName"
                                            v-else
                                            placeholder="表名"
                                            filterable
                                            style="width: 100%;"
                                            size="small"
                                            @change="tableList = [...tableList]"
                                        >
                                            <el-option
                                                v-for="(item, index) in tableList"
                                                :key="index"
                                                :label="item.tableCnName"
                                                :value="item.tableName"
                                            ></el-option>
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item style="display:inline-block">
                                        <el-button
                                            icon="el-icon-search"
                                            v-if="operate != 'edit'"
                                            type="primary"
                                            size="small"
                                            @click="search"
                                        >查询</el-button>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </el-col>
                </el-row>
                <el-table stripe
                    ref="fieldTable"
                    v-loading="fieldTable.loading"
                    border
                    :height="fieldTable.height"
                    highlight-current-row
                    :data="fieldTable.list"
                >
                    <el-table-column
                        type="index"
                        label="序号"
                        fixed="left"
                        align="center"
                    ></el-table-column>
                    <el-table-column
                        :show-overflow-tooltip="true"
                        prop="tableName"
                        label="表名"
                        min-width="90"
                    ></el-table-column>
                    <el-table-column
                        :show-overflow-tooltip="true"
                        prop="fieldName"
                        label="字段名"
                        min-width="80"
                    ></el-table-column>
                    <el-table-column
                        :show-overflow-tooltip="true"
                        prop="fieldDesc"
                        label="字段描述"
                        min-width="100"
                    ></el-table-column>
                    <el-table-column
                        :show-overflow-tooltip="true"
                        prop="isNull"
                        label="是否为空"
                        min-width="80"
                        align="center"
                    >
                        <template slot-scope="scope">
                            <span v-if="scope.row.isNull === '1'">是</span>
                            <span v-else>否</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        :show-overflow-tooltip="true"
                        label="操作"
                        fixed="right"
                        width="60"
                        align="center"
                    >
                        <template slot-scope="scope">
                            <el-button
                                class="btn-mini-select"
                                type="primary"
                                size="mini"
                                @click="fieldClick(scope.row)"
                            >选择</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
        <div class="organizManage-mainRight">
            <div class="public-function-div">{{operate === 'add' ? '添加数据权限' : '修改数据权限'}}</div>
            <div class="save">
                <el-button
                    type="primary"
                    @click="dataSave"
                    size="mini"
                >保存</el-button>
                <el-button
                    type="primary"
                    size="mini"
                    icon="el-icon-arrow-left"
                    @click="exit()"
                >返回</el-button>
            </div>
            <!--  -->
            <div class="post-m">
                <el-form
                    ref="dataTableTable"
                    :model="dataTable.table"
                >
                    <el-row>
                        <el-col :span="6">
                            <el-form-item class="rightForm">
                                <el-input
                                    :value="dataTable.table.tableCnName"
                                    disabled
                                    size="small"
                                    placeholder="表中文名"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item class="rightForm"
                                prop="tableName"
                            >
                                <el-input
                                    v-model="dataTable.table.tableName"
                                    disabled
                                    size="small"
                                    placeholder="表名"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item class="rightForm"
                                prop="operType"
                            >
                                <el-select
                                    v-model="dataTable.table.operType"
                                    placeholder="行操作类型"
                                    style="width: 100%;"
                                    size="small"
                                >
                                    <el-option
                                        v-for="item in store.state.system.dataPermissionAdd.operType"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item class="rightForm"
                                prop="authDesc"
                            >
                                <el-input
                                    v-model="dataTable.table.authDesc"
                                    size="small"
                                    placeholder="规则描述"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <el-table stripe
                    ref="dataTable"
                    v-loading="dataTable.loading"
                    border
                    :height="dataTable.height"
                    :data="dataTable.list"
                    :span-method="objectSpanMethod"
                    @selection-change="dataSelectChange"
                    @cell-click="dataCellClick"
                >
                    <el-table-column
                        :show-overflow-tooltip="true"
                        prop="fieldName"
                        label="字段名"
                        width="100"
                    ></el-table-column>
                    <el-table-column
                        :show-overflow-tooltip="true"
                        prop="isNull"
                        label="是否为空"
                        width="60"
                        align="center"
                    >
                        <template slot-scope="scope">
                            <span v-if="scope.row.isNull === '1'">是</span>
                            <span v-else>否</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        :show-overflow-tooltip="true"
                        prop="operType"
                        label="列操作类型"
                        width="80"
                    >
                        <template slot-scope="scope">
                            <el-select
                                class="where-value"
                                v-model="scope.row.operType"
                                @change="dataTableOperTypeChange"
                                placeholder="请输入"
                                style="width: 100%;"
                                size="small"
                            >
                                <!-- <el-option label="浏览" value="1"></el-option>
                <el-option label="读写" value="2"></el-option>
                <el-option label="不显示" value="3"></el-option> -->
                                <el-option
                                    v-for="item in store.state.system.dataPermissionAdd.colOperType"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column
                        :show-overflow-tooltip="true"
                        prop="operator"
                        label="行操作符"
                        width="80"
                    >
                        <template slot-scope="scope">
                            <el-select
                                class="where-value"
                                v-model="scope.row.operator"
                                placeholder="请输入"
                                style="width: 100%;"
                                size="small"
                            >
                                <!-- <el-option label="包含（in）" value="in"></el-option>
                <el-option label="等于" value="="></el-option>
                <el-option label=">" value=">"></el-option>
                <el-option label="<" value="<"></el-option>
                <el-option label=">=" value=">="></el-option>
                <el-option label="<=" value="<="></el-option>
                <el-option label="like" value="like"></el-option> -->
                                <el-option
                                    v-for="item in store.state.system.dataPermissionAdd.operator"
                                    :disabled="scope.row.dictType && scope.row.dictType.length > 0"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column
                        :show-overflow-tooltip="true"
                        prop="region"
                        label="数据授权范围"
                        width="130"
                    >
                        <template slot-scope="scope">
                            <el-select
                                class="where-value"
                                v-model="scope.row.region"
                                placeholder="请输入"
                                style="width: 100%;"
                                size="small"
                            >
                                <!-- <el-option label="当前用户" value="1"></el-option>
                <el-option label="当前机构" value="2"></el-option>
                <el-option label="当前机构(含下级)" value="3"></el-option>
                <el-option label="当前机构(含上级)" value="4"></el-option>
                <el-option label="当前角色" value="5"></el-option>
                <el-option label="实际值" value="6"></el-option> -->
                                <el-option
                                    v-for="item in store.state.system.dataPermissionAdd.region"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column
                        :show-overflow-tooltip="true"
                        prop="fieldValue"
                        label="值"
                        :min-width="190"
                    >
                        <template slot-scope="scope">
                            <!-- 值 -->
                            <el-input
                                v-if="!scope.row.dictType && scope.row.fieldType === 'VARCHAR2' || scope.row.fieldType === 'VARCHAR' || scope.row.fieldType === 'CHAR' "
                                v-model="scope.row.fieldValue"
                                @keyup.native="checkValue(scope.row)"
                                class="where-value"
                                size="mini"
                            ></el-input>
                            <el-input
                                v-else-if="!scope.row.dictType && scope.row.fieldType === 'NUMBER' || scope.row.fieldType === 'INT' || scope.row.fieldType === 'LONG'|| scope.row.fieldType === 'FLOAT'|| scope.row.fieldType === 'INTEGER' "
                                v-model.number="scope.row.fieldValue"
                                type="number"
                                @keyup.native="checkNumber(scope.row)"
                                class="where-value"
                                size="mini"
                            ></el-input>
                            <el-date-picker
                                v-else-if="!scope.row.dictType && scope.row.fieldType === 'DATE' "
                                v-model="scope.row.formatDate"
                                align="right"
                                type="datetimerange"
                                size="mini"
                                class="where-value data-value"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                @change="formatTime(scope.row)"
                            >
                            </el-date-picker>
                            <!-- 字典 -->
                            <el-select
                                v-else
                                class="where-value"
                                v-model="scope.row.fieldValue"
                                placeholder="请输入"
                                style="width: 100%;"
                                size="small"
                            >
                                <el-option
                                    v-for="item in dataDictionary.state.dict[scope.row.dictType]"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="选择"
                        width="120"
                        align="center"
                    >
                        <template slot-scope="scope">
                            <template></template>
                            <el-checkbox
                                v-model="pGroup(scope.row).checked"
                                v-if="!(pGroup(scope.row).tempPKey)"
                                @change="checkboxChange"
                            ></el-checkbox>
                            <template v-if="!(pGroup(scope.row).tempPKey)">
                                <el-tag
                                    size="mini"
                                    v-if="scope.row.restrictType === 'and'"
                                >{{scope.row.restrictType}}</el-tag>
                                <el-tag
                                    size="mini"
                                    type='success'
                                    v-else
                                >{{scope.row.restrictType}}</el-tag>
                            </template>
                            <span>{{scope.row.groupName}}</span>
                            <i
                                class="el-icon-circle-close-outline"
                                @click="closeList(pGroup(scope.row))"
                                v-if="!(pGroup(scope.row).tempPKey)"
                                style="cursor: pointer;"
                            ></i>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="组"
                        width="120"
                    >
                        <template slot-scope="scope">
                            <template v-if="colCount(scope, 7)">
                                <el-checkbox
                                    v-model="colCount(scope, 7).checked"
                                    v-if="!colCount(scope, 7).tempPKey && colCount(scope, 7).tempLevel !== 1"
                                    @change="checkboxChange"
                                ></el-checkbox>
                                <el-tag
                                    size="mini"
                                    v-if="colCount(scope, 7).restrictType === 'and'"
                                >{{colCount(scope, 7).restrictType}}</el-tag>
                                <el-tag
                                    size="mini"
                                    type='success'
                                    v-else
                                >{{colCount(scope, 7).restrictType}}</el-tag>
                                <span>{{colCount(scope, 7).groupName}}</span>
                                <i
                                    class="el-icon-circle-close-outline"
                                    @click="closeGroup(colCount(scope, 7))"
                                    v-if="colCount(scope, 7).tempLevel !== 1"
                                    style="cursor: pointer;"
                                ></i>
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="组"
                        width="120"
                    >
                        <template slot-scope="scope">
                            <template v-if="colCount(scope, 8)">
                                <el-checkbox
                                    v-model="colCount(scope, 8).checked"
                                    v-if="!colCount(scope, 8).tempPKey && colCount(scope, 8).tempLevel !== 1"
                                    @change="checkboxChange"
                                ></el-checkbox>
                                <el-tag
                                    size="mini"
                                    v-if="colCount(scope, 8).restrictType === 'and'"
                                >{{colCount(scope, 8).restrictType}}</el-tag>
                                <el-tag
                                    size="mini"
                                    type='success'
                                    v-else
                                >{{colCount(scope, 8).restrictType}}</el-tag>
                                <span>{{colCount(scope, 8).groupName}}</span>
                                <i
                                    class="el-icon-circle-close-outline"
                                    @click="closeGroup(colCount(scope, 8))"
                                    v-if="colCount(scope, 8).tempLevel !== 1"
                                    style="cursor: pointer;"
                                ></i>
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="组"
                        width="120"
                    >
                        <template slot-scope="scope">
                            <template v-if="colCount(scope, 9)">
                                <el-checkbox
                                    v-model="colCount(scope, 9).checked"
                                    v-if="!colCount(scope, 9).tempPKey && colCount(scope, 9).tempLevel !== 1"
                                    @change="checkboxChange"
                                ></el-checkbox>
                                <el-tag
                                    size="mini"
                                    v-if="colCount(scope, 9).restrictType === 'and'"
                                >{{colCount(scope, 9).restrictType}}</el-tag>
                                <el-tag
                                    size="mini"
                                    type='success'
                                    v-else
                                >{{colCount(scope, 9).restrictType}}</el-tag>
                                <span>{{colCount(scope, 9).groupName}}</span>
                                <i
                                    class="el-icon-circle-close-outline"
                                    @click="closeGroup(colCount(scope, 9))"
                                    v-if="colCount(scope, 9).tempLevel !== 1"
                                    style="cursor: pointer;"
                                ></i>
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="组"
                        width="120"
                    >
                        <template slot-scope="scope">
                            <template v-if="colCount(scope, 10)">
                                <el-checkbox
                                    v-model="colCount(scope, 10).checked"
                                    v-if="!colCount(scope, 10).tempPKey && colCount(scope, 10).tempLevel !== 1"
                                    @change="checkboxChange"
                                ></el-checkbox>
                                <el-tag
                                    size="mini"
                                    v-if="colCount(scope, 10).restrictType === 'and'"
                                >{{colCount(scope, 10).restrictType}}</el-tag>
                                <el-tag
                                    size="mini"
                                    type='success'
                                    v-else
                                >{{colCount(scope, 10).restrictType}}</el-tag>
                                <span>{{colCount(scope, 10).groupName}}</span>
                                <i
                                    class="el-icon-circle-close-outline"
                                    @click="closeGroup(colCount(scope, 10))"
                                    v-if="colCount(scope, 10).tempLevel !== 1"
                                    style="cursor: pointer;"
                                ></i>
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="组"
                        width="120"
                    ></el-table-column>
                </el-table>
                <div class="and-or">
                    <el-row>
                        <el-col>
                            <el-select
                                v-model="dataTable.andOr"
                                placeholder="请输入"
                                style="width: 100px;"
                                size="small"
                            >
                                <el-option
                                    label="and"
                                    value="and"
                                ></el-option>
                                <el-option
                                    label="or"
                                    value="or"
                                ></el-option>
                            </el-select>
                            &nbsp;&nbsp;
                            <el-button
                                type="primary"
                                size="mini"
                                :disabled="dataTable.items.length < 2"
                                @click="bindGroup"
                            >合并</el-button>
                        </el-col>

                    </el-row>
                </div>
            </div>
        </div>

    </div>

</template>
<script>
import store from '@/store/index.js';
import usersAddAndEdit from './usersAddAndEdit.vue';
import { dgTree, objAssign, createTree, dgTreeLevel } from '@/utils/util.js';
import uuid from 'node-uuid';
//  字典数据
import dataDictionary from '@/store/dataDictionary.js';
export default {
    components: {
        usersAddAndEdit
    },
    data () {
        return {
            store,
            selectStatus: '',
            dataDictionary,
            leftHeight: 600,
            operate: 'add',
            tableName: '',
            tableAuthId: '',
            //  表名列表
            tableList: [],
            //  字段列表
            fieldTable: {
                loading: false,
                height: 600,
                list: [],
                items: [],
                item: {},
                tableParams: JSON.parse(JSON.stringify(store.state.tableParams))
            },
            //  数据权限配置表格
            dataTable: {
                height: 600,
                loading: false,
                andOr: 'or',
                //  权限配置表默认数据
                dataDefault: {
                    'authDesc': '',
                    'operAction': '1',
                    'operType': '2',
                    'status': '1',
                    'sysDaColRules': [],
                    'sysDaRowRulesGroups': [],
                    'tableId': '',
                    'tableName': '',
                    'tableAuthId': ''
                },
                //  树默认结构
                groupTree: {
                    'children': [],
                    'exps': '',
                    'groupName': '',
                    // 'rank': '1',
                    'restrictType': 'or',
                    'sysDaRowRules': [],
                    //  临时UUID
                    tempKey: '',
                    //  临时上级组
                    tempPKey: ''
                },
                // // 默认条件
                // sysDaRowRules: {
                //   'fieldName': '',
                //   'operator': '',
                //   'fieldValue': '',
                //   'restrictType': '',
                //   'region': ''
                // },
                //  项默认数据
                one: {
                    fieldName: '',
                    isNull: '1',
                    operType: '2',
                    operator: '=',
                    region: '6',
                    fieldValue: '',
                    showChecked: true,
                    restrictType: 'or',
                    groupName: '组',
                    dictType: '',
                    //  =====
                    //  临时UUID
                    tempKey: '',
                    //  临时上级组
                    tempPKey: '',
                    // 字段类型
                    fieldType: '',
                    // 字段长度
                    fieldLen: ''
                },
                //  组数组
                groupTreeArr: [],
                //  生成好的树
                tree: [],
                //  数据项列表
                list: [],
                //  选中项
                items: [],
                item: {},
                //  合并单元格数据
                rowCol: [],
                //  当前表
                table: {},
                //  编辑时详情数据
                listRule: [],
                tableParams: JSON.parse(JSON.stringify(store.state.tableParams))
            }
        };
    },
    computed: {
    },
    mounted () {
        //
        this.initData();
        //
        this.$nextTick(() => {
            //  设置高度
            this.leftHeight = this.getFieldTableHeight(this.$refs['mainLeft']);
            this.fieldTable.height = this.getFieldTableHeight(this.$refs['fieldTable'].$el) - 50;
            this.dataTable.height = this.getFieldTableHeight(this.$refs['dataTable'].$el) - 70;
        });
        // //
        // this.tableHeight = this.getTableHeight(this.$refs['orgTree'].$el);
    },
    methods: {
        initData () {
            // operate
            if (this.$route.query && this.$route.query.operate) {
                this.operate = this.$route.query.operate;
            }
            // tableName
            if (this.$route.query && this.$route.query.tableName) {
                this.tableName = this.$route.query.tableName;
            }
            if (this.$route.query && this.$route.query.id) {
                this.tableAuthId = this.$route.query.id;
            }
            //  编辑
            // this.operate === 'edit' && this.getListrule(this.tableName);
            //  查询表名列表
            this.getTableList().then(() => {
                if (this.operate === 'edit') {
                    //  选中表
                    this.fieldTable.tableParams.form.tableName = this.tableName;
                    //  查询
                    this.search();
                    // this.getTableListField(this.fieldTable.tableParams.form);
                    //  查询详情
                    this.getListrule(this.tableAuthId).then(() => {
                        //  设置表数据
                        this.dataTable.table = Object.assign(this.dataTable.table, this.dataTable.listRule[0]);
                        //  整理数据
                        let data = this.editDataFn();
                        //  加入数据
                        this.dataTable.list = data.list;
                        this.dataTable.groupTreeArr = data.groupTreeArr;
                        // console.log(this.dataTable)
                        //  生成组 树形结构
                        this.dataTable.tree = this.proTreeFn();
                        //  刷新加合并单元格
                        // console.log(this.dataTable.list);
                        this.refreshTable();
                        if (this.dataTable.list.length === 0 && data.list.length === 1) {
                            this.dataTable.list = data.list;
                        }
                        this.dataTable.list = [...this.dataTable.list];
                    });
                    // console.log(this.dataTable.sysDaRowRulesGroups)
                } else {
                    this.selectStatus = '';
                }
            });
        },
        //  选择
        dataSelectChange () {
        },
        //  选择字段
        fieldClick (item) {
            let obj = Object.assign({}, this.dataTable.one);
            obj = objAssign(obj, item);
            obj.tempKey = uuid.v1();
            obj.groupName = '组' + (uuid.v1()).substr(4, 4);
            //  生成组
            let sysDaRowRulesGroups = JSON.parse(JSON.stringify(this.dataTable.groupTree));
            sysDaRowRulesGroups.tempKey = uuid.v1();
            sysDaRowRulesGroups.groupName = '组' + (uuid.v1()).substr(4, 4);
            //  条件
            obj.tempPKey = sysDaRowRulesGroups.tempKey;
            sysDaRowRulesGroups.sysDaRowRules = [obj];
            //  放入组数组
            this.dataTable.groupTreeArr.push(sysDaRowRulesGroups);
            //  生成组 树形结构
            this.dataTable.tree = this.proTreeFn();
            //  添加表格数据
            this.dataTable.list.push(obj);
            // console.log(this.dataTable.tree)
            //  刷新加合并单元格
            this.refreshTable();
        },
        //  生成组树形结构
        proTreeFn () {
            //  生成树
            if (this.operate === 'edit' && this.dataTable.groupTreeArr.length === 1) {
                this.dataTable.groupTreeArr[0].pId = '';
                this.dataTable.groupTreeArr[0].tempPKey = '';
            }
            let tree = createTree(this.dataTable.groupTreeArr, 'tempKey', 'tempPKey');
            //  如果树是只有一个不做处理，如果有多个干节点，默认合并成一个节点
            if (tree.length > 1) {
                //  生成组
                let sysDaRowRulesGroups = JSON.parse(JSON.stringify(this.dataTable.groupTree));
                // 更改and/or
                sysDaRowRulesGroups.tempKey = uuid.v1();
                sysDaRowRulesGroups.groupName = '组' + (uuid.v1()).substr(4, 4);
                //  放到一个组中
                sysDaRowRulesGroups.children = tree;
                return [sysDaRowRulesGroups];
            }
            return tree;
        },
        //  合并单元格刷新table
        refreshTable () {
            this.dataTable.rowCol = this.sumColFn();
            this.dataTable.list = [...this.dataTable.list];
        },
        //  选择改变 , 选中
        checkboxChange () {
            //  放入选中项
            this.dataTable.items = this.dataTable.groupTreeArr.filter(item => {
                if (item.checked) {
                    return true;
                } else {
                    return false;
                }
            });
        },
        //  合并组 and / or
        bindGroup () {
            let that = this;
            //  查询选中组
            let selectGroup = this.dataTable.groupTreeArr.filter(group => {
                if (group.checked) {
                    return true;
                } else {
                    return false;
                }
            });
            //  清空选中项
            this.dataTable.items = [];
            this.dataTable.groupTreeArr.forEach(item => {
                if (item.checked === true) {
                    delete item.checked;
                } else {
                    item.checked =false;
                }
            });
            this.dataTable.groupTreeArr = [...this.dataTable.groupTreeArr];
            //  生成组
            let sysDaRowRulesGroups = JSON.parse(JSON.stringify(this.dataTable.groupTree));
            sysDaRowRulesGroups.tempKey = uuid.v1();
            sysDaRowRulesGroups.groupName = '组' + (uuid.v1()).substr(4, 4);
            //  and/or
            sysDaRowRulesGroups.restrictType = this.dataTable.andOr;
            //  修改pid
            selectGroup.forEach(item => {
                item.tempPKey = sysDaRowRulesGroups.tempKey;
            });
            //  新组放入 数组中
            this.dataTable.groupTreeArr.push(sysDaRowRulesGroups);
            //  更新tree
            this.dataTable.tree = this.proTreeFn();
            //  刷新加合并单元格
            this.refreshTable();
        },
        //  保存
        dataSave () {
            let that = this;
            //  验证是否选中表
            if (Object.keys(this.dataTable.table).length < 1) {
                this.$message.error('请选择要操作的数据表');
                return false;
            }
            //  验证是否选择表操作类型
            if (this.dataTable.table.operType.toString().length < 1) {
                this.$message.error('请选择选择表操作类型');
                return false;
            }
            //  验证是否有表格数据
            if (this.dataTable.list.length < 1) {
                this.$message.error('请添加查询数据');
                return false;
            }
            // 验证是否填写值
            for (let i = 0; i < this.dataTable.list.length; i++) {
                if (!that.dataTable.list[i].fieldValue) {
                    that.$message.error('请填写值');
                    return false;
                }
            }
            //  表数据
            let data = JSON.parse(JSON.stringify(this.dataTable.dataDefault));
            data = objAssign(data, this.dataTable.table);
            //  列数据
            //  sql 语句 数据字典类型加单引号
            for (let item of this.dataTable.list) {
                if (item.dictType && item.dictType.length > 0 && item.fieldValue.length > 0 && !(item.fieldValue.indexOf('\'') === 0)) {
                    item.fieldValue = '\'' + item.fieldValue + '\'';
                }
            }
            data.sysDaColRules = this.filterCol(this.dataTable.list);
            //  行数据
            data.sysDaRowRulesGroups = this.dataTable.tree;
            //  提交数据
            if (this.operate === 'add') {
                this.addSaveSysDaTablePolicy(data);
            } else if (this.operate === 'edit') {
                this.editSaveSysDaTablePolicy(data);
            }
        },
        //  生成列操作类型数据
        filterCol (items) {
            let list = [];
            items.forEach(item => {
                list.push({
                    tableName: this.dataTable.table.tableName,
                    tableAuthId: this.dataTable.table.tableAuthId,
                    fieldName: item.fieldName,
                    operType: item.operType
                });
            });
            return list;
        },
        //  查询表名列表
        async getTableList () {
            let form = JSON.parse(JSON.stringify(store.state.tableParams.form));
            form.pageSize = '1000';
            const promise = await this.store.dispatch('system/dataPermissionAdd/tableList', form).then(res => {
                if (res.code === '0') {
                    this.tableList = res.data.list;
                } else {
                    this.$message.error(res.message);
                }
            });
            return promise;
        },
        //  读取数据权限配置记录
        async getListrule (tableAuthId) {
            const promise = await this.store.dispatch('system/dataPermissionAdd/listrule', { tableAuthId }).then(res => {
                if (res.code === '0') {
                    this.dataTable.listRule = res.data;
                    let listRuleA = res.data[0].sysDaRowRulesGroups[0].children,
                        fieldTableA = this.fieldTable.list;
                    // 给 从后台获取到的数据 增加字段类型 和长度限制
                    for (let i = 0; i < fieldTableA.length; i++) {
                        for (let b = 0; b < listRuleA.length; b++) {
                            if (listRuleA[b].sysDaRowRules.length > 0 && fieldTableA[i].fieldName === listRuleA[b].sysDaRowRules[0].fieldName) {
                                listRuleA[b].sysDaRowRules[0].fieldType = fieldTableA[i].fieldType;
                                listRuleA[b].sysDaRowRules[0].fieldLen = fieldTableA[i].fieldLen;
                            }
                        }
                    }
                    this.dataTable.listRule[0].sysDaRowRulesGroups[0].children = listRuleA;
                    // // this.tableList = res.data.list;
                    // console.log(this.dataTable.listRule);
                    this.dataTable.groupTree.restrictType = this.dataTable.listRule[0].sysDaRowRulesGroups[0].restrictType;
                } else {
                    this.$message.error(res.message);
                }
            });
            return promise;
        },
        //  查询表名 取字段
        getTableListField (form) {
            form.pageSize = '100000';
            this.store.dispatch('system/dataPermissionAdd/tableListField', form).then(res => {
                if (res.code === '0') {
                    this.fieldTable.list = res.data;
                    for (let i = 0; i < res.data.length; i++) {
                        console.log(res.data[i].fieldType)
                    }
                } else {
                    this.$message.error(res.message);
                }
            });
        },
        //  提交添加数据
        addSaveSysDaTablePolicy (form) {
            this.store.dispatch('system/dataPermissionAdd/saveSysDaTablePolicy', form).then(res => {
                if (res.code === '0') {
                    this.$message.success('添加成功');
                    console.log(res);
                    this.exit(true);
                } else {
                    this.$message.error(res.message);
                }
            });
        },
        //  提交修改数据
        editSaveSysDaTablePolicy (form) {
            this.store.dispatch('system/dataPermissionAdd/updateSysDaTablePolicy', form).then(res => {
                if (res.code === '0') {
                    this.$message.success('修改成功');
                    // console.log(res);
                    this.exit(true);
                } else {
                    this.$message.error(res.message);
                }
            });
        },
        //  合并行单无格
        objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
            for (let item of this.dataTable.rowCol) {
                if (rowIndex === item.row && columnIndex === item.col) {
                    return {
                        rowspan: item.rowspan,
                        colspan: item.colspan
                    }
                }
            }
        },
        //  写内容
        colCount (scope, colIndex) {
            let row = scope.$index;
            let col = colIndex;
            let group = null;
            //
            for (let item of this.dataTable.rowCol) {
                if (row === item.row && col === item.col) {
                    group = item.group;
                    break;
                }
            }
            if (group) {
                return group;
            }
            return '';
        },
        //  单元格点击
        dataCellClick (row, column, cell, event) {
            // console.log(row)
            // console.log(column)
            // console.log(cell)
        },
        //
        dataTableOperTypeChange () {
            //
            this.dataTable.list = [...this.dataTable.list];
        },
        //  搜索
        search () {
            if (!this.fieldTable.tableParams.form.tableName) {
                this.$message.error('请选择表');
                return false;
            }
            //  确认是否清空配置列表
            if (this.dataTable.list.length > 0) {
                this.$confirm('将清空配置表格数据，确定要切换表吗？确定请选是，取消选否。', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // 清空数据
                    this.dataTable.list = [];
                    this.dataTable.groupTreeArr = [];
                    this.dataTable.tree = [];
                    this.dataTable.items = [];
                    this.dataTable.rowCol = [];
                    //
                    this.getTableListField(this.fieldTable.tableParams.form);
                    //  放入表
                    for (let item of this.tableList) {
                        if (item.tableName === this.fieldTable.tableParams.form.tableName) {
                            //  当前表数据
                            this.dataTable.table = item;
                            //  设置默认行操作类型为2
                            this.dataTable.table.operType = '2';
                            break;
                        }
                    }
                }).catch(() => {
                    this.$message.info('已取消操作');
                    return false;
                });
            } else {
                //
                this.getTableListField(this.fieldTable.tableParams.form);
                //  放入表
                for (let item of this.tableList) {
                    if (item.tableName === this.fieldTable.tableParams.form.tableName) {
                        //  当前表数据
                        this.dataTable.table = item;
                        // // 将tableName改成tableCnName
                        // this.dataTable.table.tableName = this.dataTable.table.tableCnName;
                        //  设置默认行操作类型为2
                        this.dataTable.table.operType = '2';
                        break;
                    }
                }
            }
        },
        //  计算树区域高度
        getFieldTableHeight (dom) {
            return window.innerHeight - dom.offsetTop;
        },
        //  已有上级组不显示checked ， 如果上级组为根节点显示
        showChecked (item) {
            // if (!item) return false;
            // console.log(item)
            // let listPid = item.tempPKey;
            // let one = null;
            // this.dataTable.groupTreeArr.forEach(item => {
            //   if (item.tempKey === listPid) {
            //     one = item;
            //   }
            // });
            // //
            // if (item.tempPKey && item.tempPKey.length > 0) {
            //   return false;
            // } else {
            //   return true;
            // }
            if (item.tempPKey === '') {
                return true;
            } else {
                return false;
            }
        },
        //  找上级组
        pGroup (row) {
            for (let item of this.dataTable.groupTreeArr) {
                if (row.tempPKey === item.tempKey) {
                    return item;
                }
            }
            return '';
        },
        // ==============================================================
        //  计算合并单元格
        sumColFn () {
            let data = [];
            //  排序list 按树结构叶子递归排序
            let list = this.ascList();
            this.dataTable.list = [...list];
            //  树添加层级
            let tree = this.treeLevel(this.dataTable.tree);
            //  组的所有节点 除了根节点
            let groupList = this.groupList(tree);
            //  最大层数
            let levelMax = this.treeLevelMax(tree);
            //
            for (let item of groupList) {
                //  找所有子节点
                let child = [];
                dgTree(item.children ? item.children : [], '', item => {
                    if (!('children' in item) || (item.children && item.children.length < 1)) {
                        child.push(item);
                    }
                })
                //
                if (child.length > 0) {
                    //  行
                    let row = 0;
                    //  列
                    let col = 0;
                    //  合并行数
                    let rowspan = 1;
                    //  合并列数
                    let colspan = 1;
                    //  找第一个的下标为行数
                    for (let i = 0; i < list.length; i++) {
                        if (child[0] && child[0].sysDaRowRules[0].tempKey === list[i].tempKey) {
                            row = i;
                            break;
                        }
                    }
                    // 列为基数加 总层级减当前层级
                    col = 6 + (levelMax - item.tempLevel);
                    rowspan = child.length;
                    //
                    data.push({
                        row,
                        col,
                        rowspan,
                        colspan,
                        group: item
                    });
                }
            }
            return data;
        },
        //  对list进行排序
        ascList () {
            let tree = this.dataTable.tree;
            let list = this.dataTable.list;
            //  对list排序
            let tempArr = [];
            dgTree(tree, '', item => {
                if (!('children' in item) || (item.children && item.children.length < 1)) {
                    //  叶子节点
                    //  找list
                    if ('sysDaRowRules' in item && item.sysDaRowRules.length > 0) {
                        for (let ll of list) {
                            if (item.sysDaRowRules[0].tempKey === ll.tempKey) {
                                tempArr.push(ll);
                            }
                        }
                    }
                }
            });
            return tempArr;
        },
        //  对树添加层级
        treeLevel (tree) {
            dgTreeLevel(tree, '', () => { }, 1);
            return tree;
        },
        //  树最大层级
        treeLevelMax (tree) {
            let maxLevel = 0;
            dgTree(tree, '', item => {
                if (item.tempLevel && item.tempLevel.toString().length > 0) {
                    if (item.tempLevel > maxLevel) {
                        maxLevel = item.tempLevel;
                    }
                }
            });
            return maxLevel;
        },
        //  组的所有干节点
        groupList (tree) {
            let arr = [];
            dgTree(tree, '', item => {
                if (!('children' in item) || (item.children && item.children.length < 1)) {
                    // child.push(item);
                } else {
                    arr.push(item);
                }
            });
            return arr;
        },
        //  解除合并
        closeGroup (group) {
            //  清除下级pid
            for (let item of this.dataTable.groupTreeArr) {
                if (item.tempPKey === group.tempKey) {
                    item.tempPKey = '';
                }
            }
            let groupArr = this.dataTable.groupTreeArr;
            for (let i in groupArr) {
                if (groupArr[i].tempKey === group.tempKey) {
                    groupArr.splice(i, 1);
                }
            }
            //  生成组 树形结构
            this.dataTable.tree = this.proTreeFn();
            //  刷新加合并单元格
            this.refreshTable();
        },
        //  删除list
        closeList (group) {
            //  删除list
            if (group.sysDaRowRules && group.sysDaRowRules.length > 0) {
                let item = group.sysDaRowRules[0];
                for (let i in this.dataTable.list) {
                    if (item.tempKey === this.dataTable.list[i].tempKey) {
                        this.dataTable.list.splice(i, 1);
                        this.dataTable.tree[0].children.splice(i, 1);
                        // console.log(this.dataTable);
                        break;
                    }
                }
            }
            //  删除组
            let groupArr = this.dataTable.groupTreeArr;
            for (let i in groupArr) {
                if (groupArr[i].tempKey === group.tempKey) {
                    groupArr.splice(i, 1);
                }
            }
            //  刷新加合并单元格
            this.refreshTable();
        },
        //  编辑时整理数据显示
        editDataFn () {
            //  列操作类型
            let colList = this.dataTable.listRule[0].sysDaColRules;
            let data = this.dataTable.listRule[0].sysDaRowRulesGroups;
            let obj = {
                list: [],
                groupTreeArr: []
            }
            //  整理list
            let pidId = '';
            dgTree(data, '', item => {
                if (!('children' in item) || (item.children && item.children.length < 1)) {
                    obj.list.push(item.sysDaRowRules[0]);
                }
                //  清空根节点值0  为 ‘’ 以适应 生成树取的根节点‘’
                if (item.pId === '0') {
                    // item.pId = '';
                    pidId = item.id;
                    if (!('children' in item) || (item.children && item.children.length < 1)) {
                        obj.groupTreeArr.push(item);
                    }
                } else {
                    //  除根节点之外的组
                    obj.groupTreeArr.push(item);
                }
            });
            //  加入列操作类型
            for (let item of obj.list) {
                for (let col of colList) {
                    if (col.fieldName === item.fieldName) {
                        item.operType = col.operType;
                        break;
                    }
                }
            }
            //  清空children
            for (let item of obj.groupTreeArr) {
                item.children = [];
                //  清除二级节点的pid 编辑时不需要二级节点的pid
                if (item.pId === pidId) {
                    item.pId = '';
                }
                item.tempKey = item.id;
                item.tempPKey = item.pId;
                if ('sysDaRowRules' in item && item.sysDaRowRules.length > 0) {
                    item.sysDaRowRules[0].tempKey = item.sysDaRowRules[0].id;
                    item.sysDaRowRules[0].tempPKey = item.tempKey;
                }
            }
            return obj;
        },
        // 值校检
        checkValue (data) {
            for (let i = 0; i < this.dataTable.list.length; i++) {
                if (this.dataTable.list[i].tempKey === data.tempKey) {
                    let str = '';
                    if (data.fieldValue.indexOf("'") >= 0) {
                        if (data.fieldValue.length > data.fieldLen + 2) {
                            this.$message.error('内容长度超出限制')
                            let a = data.fieldValue.split("'");
                            a = a.join('').substr(0, data.fieldLen)
                            str = "'" + a + "'";
                        } else {
                            let a = data.fieldValue.split("'");
                            str = "'" + a.join('') + "'";
                        }
                    } else if (!data.fieldValue || data.fieldValue === ' ') {
                        this.dataTable.list[i].fieldValue = ''
                        return false
                    } else {
                        str = "'" + data.fieldValue + "'"
                    }
                    this.dataTable.list[i].fieldValue = str;
                }
            }
        },
        // 格式化时间
        formatTime (data) {
            let time = data,
                formatTime = "to_char('" + data.formatDate[0] + "','yyyy-mm-dd hh24:mi:ss')='" + data.formatDate[1] + "'";
            for (let i = 0; i < this.dataTable.list.length; i++) {
                if (this.dataTable.list[i].tempKey === data.tempKey) {
                    this.dataTable.list[i].fieldValue = formatTime;
                }
            }
        },
        // 数字长度校检
        checkNumber (data) {
            // let val = data.fieldValue,
            //   len = data.fieldLen;
            // if (len && val > len) {
            //   debugger
            //   for (let i = 0; i < this.dataTable.list.length; i++) {

            //   }
            // }
        },
        // ============================================================
        exit (qd = false) {
            if (qd) {
                this.$router.push({ path: '/dataPermission' });
            } else {
                this.$confirm('是否返回数据权限列表？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$router.push({ path: '/dataPermission' });
                }).catch(() => {
                });
            }
        }
    }
};
</script>

<style lang="less" scoped>
.data-permission-add {
    position: relative;
    min-width: 800px;
    .organizManage-mainLeft {
        width: 40%;
        height: inherit;
    }
    .organizManage-mainRight {
        width: 60%;
        position: relative;
        .save {
            position: absolute;
            right: 20px;
            top: 8px;
        }
    }
    .and-or {
        margin-top: 10px;
        text-align: right;
    }
    .where-value {
        input {
            border-radius: 0;
            height: 20px;
            line-height: 20px;
        }
        .el-select-dropdown__item {
            height: 26px;
            line-height: 26px;
        }
    }
    //  选择字段按钮
    .btn-mini-select {
        padding: 3px 6px;
    }
}

.og-st-ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    word-break: keep-all;
    padding-right: 60px;
}

.organizManage-main {
    height: 600px;
}

.public-function-div {
    font-size: 16px;
    padding: 10px 20px;
    border-bottom: 1px solid #d5d5d5;
}

.organizManage-mainLeft {
    width: 30%;
    border-right: 1px solid #e0e0e0;
    float: left;
    overflow-x: hidden;
}

.organizManage-mainRight {
    width: 70%;
    float: left;
}

.FormorganizManage-main {
    margin: 20px 20px;
}
.post-m {
    margin: 20px;
}
.data-value {
    width: 100% !important;
}
.errorStatus {
    input {
        border-color: #f00;
    }
}
.rightForm {
    // width: 90%;
    margin-right: 10px;
}
</style>
