<!--业务编码规则-->
<template>
    <div class="BusinessCodeRules">
        <!-- <div class="title-box">
            <el-button
                style="float: right;margin: 10px 0;"
                type="primary"
                size="medium"
                icon="el-icon-arrow-left"
                @click="exit()"
            >返回</el-button>
        </div> -->
        <div class="BusinessCodeRules-box">
            <div class="box">
                <el-form
                    label-width="85px"
                    inline
                >
                    <el-form-item label="编码规则名：">
                        <el-input
                            size="mini"
                            style="width: 350px;"
                            v-model="builder.codeName"
                            disabled
                        ></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button
                            class="button"
                            type="primary"
                            icon="el-icon-plus"
                            size="mini"
                            @click="codeRule_handle({str:'add',row:''})"
                            :loading="loading"
                        >新增规则</el-button>
                        <el-button
                            class="button"
                            type="primary"
                            icon="el-icon-setting"
                            size="mini"
                            @click="getCodeExample()"
                            :loading="loading"
                        >测试</el-button>
                    </el-form-item>
                    <el-button
                        style="float: right;"
                        type="primary"
                        size="mini"
                        icon="el-icon-arrow-left"
                        @click="exit()"
                    >返回</el-button>
                </el-form>
                <el-table
                    ref="singleTable"
                    v-loading="tableLoading"
                    :data="tableData"
                    style="width: 100%;margin-top: 10px;"
                    border
                    size="mini"
                    highlight-current-row
                    @current-change="handleCurrentChange"
                >
                    <el-table-column
                        prop="order"
                        label="顺序"
                        align="center"
                        :show-overflow-tooltip="true"
                        min-width="60px"
                    ></el-table-column>
                    <el-table-column
                        label="规则类型"
                        :show-overflow-tooltip="true"
                        min-width="120px"
                    >
                        <template slot-scope="scope">
                            <span>{{ ruleTypeName[scope.row.ruleType].value }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="attribute"
                        label="取值属性"
                        :show-overflow-tooltip="true"
                        min-width="95px"
                    ></el-table-column>
                    <el-table-column
                        prop="display"
                        label="显示格式"
                        :show-overflow-tooltip="true"
                        min-width="120px"
                    ></el-table-column>
                    <el-table-column
                        prop="length"
                        label="长度"
                        :show-overflow-tooltip="true"
                        min-width="70px"
                    ></el-table-column>
                    <el-table-column
                        prop="initial"
                        label="初始值"
                        :show-overflow-tooltip="true"
                        min-width="90px"
                    ></el-table-column>
                    <el-table-column
                        prop="max"
                        label="最大值"
                        :show-overflow-tooltip="true"
                        min-width="90px"
                    ></el-table-column>
                    <el-table-column
                        prop="stepLength"
                        label="步长"
                        :show-overflow-tooltip="true"
                        min-width="90px"
                    ></el-table-column>
                    <el-table-column
                        label="是否可循环"
                        align="center"
                        min-width="90px"
                        :show-overflow-tooltip="true"
                    >
                        <template slot-scope="scope">
                            <span>{{ scope.row.recyclable === '1' ? '是' : scope.row.recyclable === '0' ? '否' : '' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="状态"
                        align="center"
                        :show-overflow-tooltip="true"
                        width="70px"
                    >
                        <template slot-scope="scope">
                            <span :class="{chartreuse: scope.row.state === '1', red: scope.row.state === '0'}">{{ scope.row.state === '1' ? '启用' : scope.row.state === '0' ? '停用' : '' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="操作"
                        align="center"
                        width="100px"
                        fixed="right"
                    >
                        <template slot-scope="scope">
                            <el-button
                                type="text"
                                @click="codeRule_handle({str:'del', row:scope.row})"
                                @click.stop
                                :loading="loading"
                            >删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- <div style="text-align: left;">
                    <span
                        style="color:#409EFF;cursor:pointer;"
                        @click="getCodeExample()"
                    >生成业务编码样例</span>
                    <span>：{{ codeExample.code }}</span>
                </div> -->
            </div>
        </div>
        <div
            v-show="dialog_Rule.show"
            class="dialogRule-box"
        >
            <div style="padding: 5px 20px 10px;">
                <div class="edit-flag">
                    <span class="span-text">编辑区-{{ dialog_Rule.state }}</span>
                </div>
                <el-form
                    size="mini"
                    :model="dialog_Rule.form.data"
                    :rules="dialog_Rule.form.rules"
                    ref="dialog_Rule_form"
                    label-width="100px"
                >
                    <div class="editor-box">
                        <el-row>
                            <el-col :span="6">
                                <el-form-item
                                    label="规则类型"
                                    prop="ruleType"
                                >
                                    <el-select
                                        size="mini"
                                        class="BusinessCodeRules-width-100"
                                        v-model="dialog_Rule.form.data.ruleType"
                                        @change="dialog_Rule_ruleType()"
                                        :disabled="dialog_Rule.state === '修改'"
                                    >
                                        <el-option
                                            v-for="(value, key) in ruleTypeName"
                                            v-show="value.show"
                                            :key="key"
                                            :label="value.value"
                                            :value="key"
                                        ></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item
                                    label="排列顺序"
                                    v-if="dialog_Rule.form.show.order"
                                    prop="order"
                                >
                                    <el-input-number
                                        size="mini"
                                        class="BusinessCodeRules-width-100 el-input-number-text-left"
                                        controls-position="right"
                                        :min="1"
                                        :max="dialog_Rule.state === '修改' ? tableData.length : tableData.length + 1"
                                        v-model.number="dialog_Rule.form.data.order"
                                    ></el-input-number>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item
                                    label="状态"
                                    v-if="dialog_Rule.form.show.state"
                                    prop="state"
                                >
                                    <el-select
                                        size="mini"
                                        class="BusinessCodeRules-width-100"
                                        v-model="dialog_Rule.form.data.state"
                                    >
                                        <el-option
                                            label="启用"
                                            value="1"
                                        ></el-option>
                                        <el-option
                                            label="停用"
                                            value="0"
                                        ></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item
                                    label="机构名"
                                    v-if="dialog_Rule.form.data.ruleType === '3'"
                                >
                                    <el-input
                                        size="mini"
                                        class="BusinessCodeRules-width-100"
                                        :value="dialog_Rule.state === '新增' ? userInfo.orgCode : dialog_Rule.form.data.attribute"
                                        disabled
                                    ></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item
                                    :label="dialog_Rule.form.data.ruleType === '1' ? '值' : dialog_Rule.form.data.ruleType === '4' ? '字段名' : '取值属性'"
                                    v-if="dialog_Rule.form.show.attribute"
                                    prop="attribute"
                                >
                                    <el-input
                                        v-if="dialog_Rule.form.data.ruleType !== '4'"
                                        size="mini"
                                        class="BusinessCodeRules-width-100"
                                        v-model.trim="dialog_Rule.form.data.attribute"
                                    ></el-input>
                                    <el-select
                                        v-else
                                        size="mini"
                                        class="BusinessCodeRules-width-100"
                                        v-model="dialog_Rule.form.data.attribute"
                                        filterable
                                    >
                                        <el-option
                                            v-for="(item, index) of tableFields"
                                            :key="index"
                                            :value="item.value"
                                        ></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item
                                    label="显示格式"
                                    v-if="dialog_Rule.form.show.display"
                                    prop="display"
                                >
                                    <!-- <el-select
                                        size="mini"
                                        class="BusinessCodeRules-width-100"
                                        popper-class="my-autocomplete"
                                        v-model="dialog_Rule.form.data.display"
                                        placeholder="请选择日期格式"
                                    >
                                        <el-option
                                            v-for="item in dateDisplay"
                                            :key="item.value"
                                            :label="item.value"
                                            :value="item.value"
                                        >
                                            <div class="value">{{ item.value }}</div>
                                            <span class="addr">{{ item.label }}</span>
                                        </el-option>
                                    </el-select> -->
                                    <el-autocomplete
                                        size="mini"
                                        class="BusinessCodeRules-width-100"
                                        popper-class="my-autocomplete"
                                        ref="dialog_Rule_form_display"
                                        v-model="dialog_Rule.form.data.display"
                                        :fetch-suggestions="displayQS"
                                        placeholder="日期格式，如：yyyyMMddHHmmss"
                                        @select="displayQSSelect"
                                    >
                                        <template slot-scope="{ item }">
                                            <div class="value">{{ item.value }}</div>
                                            <span class="addr">{{ item.label }}</span>
                                        </template>
                                    </el-autocomplete>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item
                                    label="长度"
                                    v-if="dialog_Rule.form.show.length && dialog_Rule.form.data.ruleType !==  '5'"
                                    prop="length"
                                    :rules="[{required: dialog_Rule.form.data.ruleType !==  '4', message:'该项不能为空'}, ...dialog_Rule.form.rules.length]"
                                >
                                    <el-input
                                        size="mini"
                                        class="BusinessCodeRules-width-100"
                                        v-model.number="dialog_Rule.form.data.length"
                                    ></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item
                                    label="初始值"
                                    v-if="dialog_Rule.form.show.initial"
                                    prop="initial"
                                >
                                    <el-input
                                        size="mini"
                                        class="BusinessCodeRules-width-100"
                                        v-model.number="dialog_Rule.form.data.initial"
                                        :disabled="dialog_Rule.state === '修改'"
                                    ></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item
                                    label="最大值"
                                    v-if="dialog_Rule.form.show.max"
                                    prop="max"
                                >
                                    <el-input
                                        size="mini"
                                        class="BusinessCodeRules-width-100"
                                        v-model.number="dialog_Rule.form.data.max"
                                        :disabled="dialog_Rule.state === '修改'"
                                    ></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item
                                    label="步长"
                                    v-if="dialog_Rule.form.show.stepLength"
                                    prop="stepLength"
                                >
                                    <el-input
                                        size="mini"
                                        class="BusinessCodeRules-width-100"
                                        v-model.number="dialog_Rule.form.data.stepLength"
                                        :disabled="dialog_Rule.state === '修改'"
                                    ></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item
                                    label="是否可循环"
                                    v-if="dialog_Rule.form.show.recyclable"
                                    prop="recyclable"
                                >
                                    <el-select
                                        size="mini"
                                        class="BusinessCodeRules-width-100"
                                        v-model="dialog_Rule.form.data.recyclable"
                                        :disabled="dialog_Rule.state === '修改'"
                                    >
                                        <el-option
                                            label="是"
                                            value="1"
                                        ></el-option>
                                        <el-option
                                            label="否"
                                            value="0"
                                        ></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <div class="editor-but">
                            <el-button
                                size="mini"
                                @click="cancelBut()"
                                :loading="loading"
                            >取 消</el-button>
                            <el-button
                                type="primary"
                                size="mini"
                                @click="formSubmit_dialog_Rule()"
                                :loading="loading"
                            >保 存</el-button>
                        </div>
                    </div>
                </el-form>
            </div>
        </div>
        <el-dialog
            title="业务编码"
            :visible.sync="codeExample.show"
            width="350px"
        >
            <div style="padding-bottom:20px;">
                <p>编码：{{ codeExample.code }}</p>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { checkComplexText } from '@/utils/validator.js'
import store from '@/store/index.js';
export default {
    name: 'BusinessCodeRules',
    data () {
        const checkPositiveInteger = (rule, value, callback) => {
            if (value || value === 0) {
                let st = /^[1-9][0-9]*$/;
                if (!st.test(value)) {
                    return callback(new Error('请输入正整数'));
                }
                if (rule.max && value > rule.max) {
                    return callback(new Error('值不能超过' + rule.max));
                }
                if (rule.min && value < rule.min) {
                    return callback(new Error('值不能小于' + rule.min));
                }
            }
            callback();
        };
        const checkMax = (rule, value, callback) => {
            let that = this;
            if (value) {
                if (value < that.dialog_Rule.form.data.initial) {
                    return callback(new Error('最大值不能小于初始值'));
                }
            }
            callback();
        };
        const checkStepLength = (rule, value, callback) => {
            let that = this;
            if (value) {
                if (value > that.dialog_Rule.form.data.max) {
                    return callback(new Error('步长不能大于最大值'));
                }
            }
            callback();
        };
        const checkDisplay = (rule, value, callback) => {
            let st = /^[yYMdDwWhHmsSa/:-]*$/;
            if (!st.test(value)) {
                return callback(new Error('请输入正确的日期时间格式'));
            }
            callback();
        };
        return {
            store,
            userInfo: {}, // 用户信息
            loading: false,
            tableLoading: false,
            ruleTypeName: {
                1: { value: '固定值', show: true },
                2: { value: '当前日期', show: true },
                3: { value: '当前机构', show: true },
                4: { value: '对象属性（字段名）', show: true },
                5: { value: '流水号', show: true }
            },
            tableFields: [],
            tableData: [],
            codeExample: {
                show: false,
                code: ''
            },
            dateDisplay: [
                { value: 'yyyyMMddHHmmss', label: '年月日时分秒', length: 14 },
                { value: 'yyyyMMdd', label: '年月日', length: 8 },
                { value: 'yyyyMM', label: '年月', length: 6 }
            ],
            dialog_Rule: {
                state: '',
                show: false,
                form: {
                    data: {
                        id: '',
                        ruleType: '', // 规则类型
                        attribute: '', // 取值属性
                        display: 'yyyyMMddHHmmss', // 显示格式
                        length: '5', // 长度
                        initial: '1', // 初始值
                        max: '10000', // 最大值
                        stepLength: '1', // 步长
                        recyclable: '1', // 是否可循环
                        order: '', // 排列顺序
                        state: '1' // 状态
                    },
                    rules: {
                        ruleType: [
                            { required: true, message: '该项不能为空', trigger: 'change' }
                        ],
                        attribute: [
                            { required: true, message: '该项不能为空', trigger: 'blur' },
                            { validator: checkComplexText, max: 100, trigger: 'change' }
                        ],
                        display: [
                            { required: true, message: '该项不能为空', trigger: 'change' },
                            { validator: checkDisplay, trigger: 'change' }
                        ],
                        length: [
                            { validator: checkPositiveInteger, trigger: 'change' }
                        ],
                        initial: [
                            { required: true, message: '该项不能为空', trigger: 'change' },
                            { validator: checkPositiveInteger, trigger: 'change' }
                        ],
                        max: [
                            { required: true, message: '该项不能为空', trigger: 'change' },
                            { validator: checkPositiveInteger, trigger: 'change' },
                            { validator: checkMax, trigger: 'change' }
                        ],
                        stepLength: [
                            { required: true, message: '该项不能为空', trigger: 'change' },
                            { validator: checkPositiveInteger, trigger: 'change' },
                            { validator: checkStepLength, trigger: 'change' }
                        ],
                        recyclable: [
                            { required: true, message: '该项不能为空', trigger: 'change' }
                        ],
                        order: [
                            { required: true, message: '该项不能为空', trigger: 'blur' }
                        ],
                        state: [
                            { required: true, message: '该项不能为空', trigger: 'change' }
                        ]
                    },
                    show: {
                        attribute: false,
                        display: false,
                        length: false,
                        initial: false,
                        max: false,
                        stepLength: false,
                        recyclable: false,
                        order: false,
                        state: false
                    },
                    disabled: {
                        attribute: true
                    }
                }
            }
        };
    },
    props: {
        builder: {
            type: Object,
            default: function () {
                return {
                    show: false,
                    data: {
                        id: '',
                        codeName: ''
                    }
                };
            }
        }
    },
    mounted () {
        this.getDialog_codeRule_tableData();
        // 获取用户信息
        this.store.dispatch('getUserInfo').then((res) => {
            this.userInfo = res.data;
        });
        this.getDataTableName();
    },
    methods: {
        getDialog_codeRule_tableData () {
            let that = this;
            that.tableData = [];
            that.tableLoading = true;
            that.axios.get('pass/v1/syscodepatterns/queryByBuilderId/?builderId=' + that.builder.id)
                .then(function (res) {
                    if (res.code === '0') {
                        let arr = [];
                        res.data.forEach(item => {
                            arr.push({
                                id: item.codePatternId,
                                ruleType: item.patternType, // 规则类型
                                attribute: item.valueField, // 取值属性
                                display: item.valueFmt, // 显示格式
                                length: item.valueLen, // 长度
                                initial: item.valueDef, // 初始值
                                max: item.valueMax, // 最大值
                                stepLength: item.valueStep, // 步长
                                recyclable: item.isLoop, // 是否可循环
                                order: item.patternSeq, // 排列顺序
                                state: item.status // 状态
                            });
                        });
                        that.$refs['singleTable'].setCurrentRow();
                        that.tableData = arr;
                        that.tableLoading = false;
                        // that.getCodeExample();
                    } else {
                        that.tableLoading = false;
                        that.$message.error(res.message);
                    }
                }).catch(function () {
                    that.tableLoading = false;
                });
        },
        getCodeExample () {
            let that = this;
            // 只提交启用的规则
            let codeRuleList = [];
            for (let item of that.tableData) {
                if (item.state === '1') {
                    codeRuleList.push({
                        codePatternId: item.id,
                        patternType: item.ruleType,
                        valueField: item.attribute,
                        valueFmt: item.display,
                        valueLen: item.length,
                        valueDef: item.initial,
                        valueMax: item.max,
                        valueStep: item.stepLength,
                        isLoop: item.recyclable,
                        patternSeq: item.order,
                        status: item.state
                    });
                }
            }
            if (codeRuleList.length > 0) {
                that.codeExample.show = true;
                that.codeExample.code = '正在获取中...';
                that.axios.post('pass/v1/syscodebuilders/generateOneCode?builderType=' + encodeURIComponent(that.builder.codeName), {
                    codeRuleList: codeRuleList
                }, {
                        diy: true,
                        headers: {
                            'Content-Type': 'application/json;charset=UTF-8'
                        }
                    })
                    .then(function (res) {
                        if (res.code === '0') {
                            that.codeExample.code = res.data;
                        } else {
                            that.codeExample.code = '生成失败，请尝试修改编码规则！';
                            that.$message.error(res.message);
                        }
                    }).catch(function () {
                        that.codeExample.code = '生成失败，请尝试修改编码规则！';
                    });
            } else {
                that.codeExample.code = '请先完善编码规则！';
            }
        },
        // 取消
        cancelBut () {
            let that = this;
            that.$refs['singleTable'].setCurrentRow();
            that.dialog_Rule.show = false;
        },
        // 修改选择行
        handleCurrentChange (row) {
            let that = this;
            if (row && !that.loading) {
                that.codeRule_handle({ str: 'edit', row: row });
            }
        },
        codeRule_handle (command) {
            let str = command.str, row = command.row,
                that = this;
            switch (str) {
                case 'add':
                    for (let key in that.ruleTypeName) {
                        that.ruleTypeName[key].show = true;
                    }
                    // 将已存在的规则类型隐藏起来，避免用户重复添加
                    that.tableData.forEach(item => {
                        if (that.ruleTypeName[item.ruleType].value !== '固定值') {
                            that.ruleTypeName[item.ruleType].show = false;
                        }
                    });
                    // 设置默认规则类型
                    let ruleTypeDefault = '1';
                    for (let key in that.ruleTypeName) {
                        if (that.ruleTypeName[key].value !== '固定值' && that.ruleTypeName[key].show) {
                            ruleTypeDefault = key;
                            break;
                        }
                    }
                    that.$refs['singleTable'].setCurrentRow();
                    that.dialog_Rule.state = '新增';
                    that.dialog_Rule.form.data = {
                        id: '',
                        ruleType: '', // 规则类型
                        attribute: '', // 取值属性
                        display: '', // 显示格式
                        length: '', // 长度
                        initial: '', // 初始值
                        max: '', // 最大值
                        stepLength: '', // 步长
                        recyclable: '', // 是否可循环
                        order: '', // 排列顺序
                        state: '' // 状态
                    }
                    that.dialog_Rule_ruleType(ruleTypeDefault);
                    that.dialog_Rule.show = true;
                    setTimeout(() => {
                        that.$refs['dialog_Rule_form'].resetFields();
                        that.dialog_Rule.form.data.ruleType = ruleTypeDefault; // 设置规则类型
                        for (let i = 1; ; i++) {
                            let tg = true;
                            for (let u = 0; u < that.tableData.length; u++) {
                                if (+that.tableData[u].order === i) {
                                    tg = false;
                                    break;
                                }
                            }
                            if (tg) {
                                that.dialog_Rule.form.data.order = i;
                                break;
                            }
                        }
                    }, 100);
                    break;
                case 'edit':
                    that.dialog_Rule.state = '修改';
                    that.dialog_Rule.form.data = {
                        id: row.id,
                        ruleType: row.ruleType,
                        attribute: row.attribute,
                        display: row.display,
                        length: row.length,
                        initial: row.initial,
                        max: row.max,
                        stepLength: row.stepLength,
                        recyclable: row.recyclable,
                        order: row.order,
                        state: row.state
                    }
                    that.dialog_Rule_ruleType();
                    that.$refs['dialog_Rule_form'].validate((valid) => { });
                    that.dialog_Rule.show = true;
                    break;
                case 'del':
                    that.cancelBut();
                    that.$confirm('此操作将删除该条编码规则, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        state: 'warning'
                    }).then(() => {
                        // 删除的同时将其后的排序进行调整
                        let codeRuleList = [];
                        for (let item of that.tableData) {
                            if (item.order > row.order) {
                                codeRuleList.push({
                                    codePatternId: item.id,
                                    patternSeq: item.order - 1
                                })
                            }
                        }
                        that.loading = true;
                        that.axios.delete('pass/v1/syscodepatterns/deleteOnePattern?id=' + row.id, {
                            data: {
                                codeRuleList: codeRuleList
                            },
                            diy: true,
                            headers: {
                                'Content-Type': 'application/json;charset=UTF-8'
                            }
                        })
                            .then(function (res) {
                                if (res.code === '0') {
                                    for (let i = 0; i < that.tableData.length; i++) {
                                        if (row.id === that.tableData[i].id) {
                                            that.tableData.splice(i, 1);
                                        }
                                    }
                                    for (let item of codeRuleList) {
                                        for (let i = 0; i < that.tableData.length; i++) {
                                            if (item.codePatternId === that.tableData[i].id) {
                                                that.tableData[i].order = item.patternSeq;
                                            }
                                        }
                                    }
                                    that.tableOrder();
                                    // that.getCodeExample();
                                    that.$message({
                                        message: '删除成功',
                                        type: 'success'
                                    });
                                } else {
                                    that.$message.error(res.message);
                                }
                                that.loading = false;
                            }).catch(function () {
                                that.loading = false;
                            });
                    }).catch(() => {
                    });
                    break;
            }
        },
        // 新增或修改业务编码规则
        formSubmit_dialog_Rule () {
            let that = this,
                obj = {
                    ruleType: { lab: 'patternType', val: that.dialog_Rule.form.data.ruleType },
                    attribute: { lab: 'valueField', val: that.dialog_Rule.form.data.attribute },
                    display: { lab: 'valueFmt', val: that.dialog_Rule.form.data.display },
                    length: { lab: 'valueLen', val: that.dialog_Rule.form.data.length },
                    initial: { lab: 'valueDef', val: that.dialog_Rule.form.data.initial },
                    max: { lab: 'valueMax', val: that.dialog_Rule.form.data.max },
                    stepLength: { lab: 'valueStep', val: that.dialog_Rule.form.data.stepLength },
                    recyclable: { lab: 'isLoop', val: that.dialog_Rule.form.data.recyclable },
                    order: { lab: 'patternSeq', val: that.dialog_Rule.form.data.order },
                    state: { lab: 'status', val: that.dialog_Rule.form.data.state }
                },
                SubmitData = {};
            that.$refs['dialog_Rule_form'].validate((valid) => {
                if (valid) {
                    that.loading = true;
                    // 筛选，只添加需要提交的项
                    for (let key in obj) {
                        if (that.dialog_Rule.form.show.hasOwnProperty(key)) {
                            if (that.dialog_Rule.form.show[key]) {
                                SubmitData[obj[key].lab] = obj[key].val;
                            }
                        } else {
                            SubmitData[obj[key].lab] = obj[key].val;
                        }
                    }
                    // 自动修改长度属性
                    // if (SubmitData.valueFmt) {
                    //     that.dateDisplay.forEach(item => {
                    //         if (SubmitData.valueFmt === item.value) {
                    //             SubmitData.valueLen = item.length;
                    //         }
                    //     });
                    // }
                    if (SubmitData.valueMax) {
                        SubmitData.valueLen = (SubmitData.valueMax + '').length;
                    }
                    // 找出需要调整循序的数据
                    let objOrder = that.tableData.length + 1, // 新增(修改)数据的原始循序
                        codeRuleList = []; // 需要调整循序的数据列表
                    for (let i = 0; i < that.tableData.length; i++) {
                        if (that.tableData[i].id === that.dialog_Rule.form.data.id) { // 找出修改目标的原始循序
                            objOrder = that.tableData[i].order;
                            break;
                        }
                    }
                    for (let item of that.tableData) {
                        if (objOrder > that.dialog_Rule.form.data.order) { // 前移
                            if (item.order >= that.dialog_Rule.form.data.order && item.order < objOrder) {
                                codeRuleList.push({
                                    codePatternId: item.id,
                                    patternSeq: item.order + 1 // 受影响的数据后移
                                })
                            }
                        } else if (objOrder < that.dialog_Rule.form.data.order) { // 后移
                            if (item.order <= that.dialog_Rule.form.data.order && item.order > objOrder) {
                                codeRuleList.push({
                                    codePatternId: item.id,
                                    patternSeq: item.order - 1 // 受影响的数据前移
                                })
                            }
                        } else {
                            break;
                        }
                    }
                    if (that.dialog_Rule.state === '新增') {
                        let foorData = new FormData();
                        foorData.append('builderId', that.builder.id);
                        for (let key in SubmitData) {
                            foorData.append(key, SubmitData[key]);
                        }
                        // 新增规则并选择当前机构时,将机构名上传
                        if (that.dialog_Rule.form.data.ruleType === '3') {
                            foorData.append('valueField', that.userInfo.orgCode);
                        }
                        that.axios.post('pass/v1/syscodepatterns/', foorData, {
                            headers: {
                                'Content-Type': 'multipart/form-data'
                            }
                        })
                            .then(function (res) {
                                if (res.code === '0') {
                                    let addObj = {
                                        id: res.data.codePatternId,
                                        ruleType: res.data.patternType, // 规则类型
                                        attribute: res.data.valueField, // 取值属性
                                        display: res.data.valueFmt, // 显示格式
                                        length: res.data.valueLen, // 长度
                                        initial: res.data.valueDef, // 初始值
                                        max: res.data.valueMax, // 最大值
                                        stepLength: res.data.valueStep, // 步长
                                        recyclable: res.data.isLoop, // 是否可循环
                                        order: res.data.patternSeq, // 排列顺序
                                        state: res.data.status // 状态
                                    };
                                    that.tableData.push(addObj);
                                    let thenFoo = () => {
                                        that.loading = false;
                                        that.dialog_Rule.show = false;
                                        that.$message({
                                            message: '新增成功',
                                            type: 'success'
                                        });
                                    };
                                    if (codeRuleList.length > 0) {
                                        that.batchUpdate(codeRuleList, () => {
                                            that.tableOrder();
                                            that.$refs['singleTable'].setCurrentRow(addObj);
                                            // that.getCodeExample();
                                            thenFoo();
                                        }, () => {
                                            that.tableOrder();
                                            that.$refs['singleTable'].setCurrentRow(addObj);
                                            // that.getCodeExample();
                                            that.loading = false;
                                            that.dialog_Rule.show = false;
                                        });
                                    } else {
                                        that.tableOrder();
                                        that.$refs['singleTable'].setCurrentRow(addObj);
                                        // that.getCodeExample();
                                        thenFoo();
                                    }
                                } else {
                                    that.loading = false;
                                    that.$message.error(res.message);
                                }
                            }).catch(function () {
                                that.loading = false;
                            });
                    } else if (that.dialog_Rule.state === '修改') {
                        that.axios.put('pass/v1/syscodepatterns/' + that.dialog_Rule.form.data.id, SubmitData)
                            .then(function (res) {
                                if (res.code === '0') {
                                    let row = null;
                                    for (let i = 0; i < that.tableData.length; i++) {
                                        if (that.dialog_Rule.form.data.id === that.tableData[i].id) {
                                            row = that.tableData[i];
                                            let editObj = {
                                                id: res.data.codePatternId,
                                                ruleType: res.data.patternType, // 规则类型
                                                attribute: res.data.valueField, // 取值属性
                                                display: res.data.valueFmt, // 显示格式
                                                length: res.data.valueLen, // 长度
                                                initial: res.data.valueDef, // 初始值
                                                max: res.data.valueMax, // 最大值
                                                stepLength: res.data.valueStep, // 步长
                                                recyclable: res.data.isLoop, // 是否可循环
                                                order: res.data.patternSeq, // 排列顺序
                                                state: res.data.status // 状态
                                            };
                                            for (let key in editObj) {
                                                that.tableData[i][key] = editObj[key];
                                            }
                                            break;
                                        }
                                    }
                                    let thenFoo = () => {
                                        that.loading = false;
                                        that.dialog_Rule.show = false;
                                        that.$message({
                                            message: '修改成功',
                                            type: 'success'
                                        });
                                    }
                                    if (codeRuleList.length > 0) {
                                        that.batchUpdate(codeRuleList, () => {
                                            that.tableOrder();
                                            that.$refs['singleTable'].setCurrentRow(row);
                                            // that.getCodeExample();
                                            thenFoo();
                                        }, () => {
                                            that.tableOrder();
                                            that.$refs['singleTable'].setCurrentRow(res);
                                            // that.getCodeExample();
                                            that.loading = false;
                                            that.dialog_Rule.show = false;
                                        });
                                    } else {
                                        that.tableOrder();
                                        that.$refs['singleTable'].setCurrentRow(res);
                                        // that.getCodeExample();
                                        thenFoo();
                                    }
                                } else {
                                    that.$message.error(res.message);
                                }
                                that.loading = false;
                            }).catch(function () {
                                that.loading = false;
                            });
                    }
                } else {
                    return false;
                }
            });
        },
        // 批量修改（发送数据至后台）
        batchUpdate (codeRuleList, thenFoo, catchFoo) {
            let that = this;
            let cObj = {
                codePatternId: 'id',
                patternType: 'ruleType',
                valueField: 'attribute',
                valueFmt: 'display',
                valueLen: 'length',
                valueDef: 'initial',
                valueMax: 'max',
                valueStep: 'stepLength',
                isLoop: 'recyclable',
                patternSeq: 'order',
                status: 'state'
            }
            that.axios.put('pass/v1/syscodepatterns/batchUpdate', {
                codeRuleList: codeRuleList
            })
                .then(function (res) {
                    if (res.code === '0') {
                        for (let item of codeRuleList) {
                            for (let i = 0; i < that.tableData.length; i++) {
                                if (item.codePatternId === that.tableData[i].id) {
                                    for (let key in item) {
                                        that.tableData[i][cObj[key]] = item[key];
                                    }
                                }
                            }
                        }
                        if (thenFoo) {
                            thenFoo();
                        }
                    } else {
                        if (catchFoo) {
                            catchFoo();
                        }
                        that.$message.error(res.message);
                    }
                }).catch(function () {
                    if (catchFoo) {
                        catchFoo();
                    }
                });
        },
        // 将表格内的数据按排序属性的值进行升序排序
        tableOrder () {
            let that = this;
            for (let i = 0; i < that.tableData.length; i++) {
                let min = i;
                for (let u = i + 1; u < that.tableData.length; u++) {
                    if (that.tableData[min].order > that.tableData[u].order) {
                        min = u;
                    }
                }
                if (min !== i) {
                    let obj = that.tableData[i];
                    that.tableData[i] = that.tableData[min];
                    that.tableData[min] = obj;
                }
            }
        },
        // 根据规则类型显示要输入的项
        dialog_Rule_ruleType (type) {
            let that = this;
            let ruleType = type || that.dialog_Rule.form.data.ruleType;
            if (that.dialog_Rule.state === '新增') {
                that.dialog_Rule.form.data.state = '1'; // 状态默认为启用
            }
            switch (ruleType) {
                case '1': // 固定值（前缀）
                    that.dialog_Rule.form.show = {
                        attribute: true,
                        display: false,
                        length: false,
                        initial: false,
                        max: false,
                        stepLength: false,
                        recyclable: false,
                        order: true,
                        state: true
                    };
                    if (that.dialog_Rule.state === '新增') {
                        that.dialog_Rule.form.data.attribute = '-'; // 固定值(分隔符)的默认值
                    }
                    break;
                case '2': // 当前日期
                    that.dialog_Rule.form.show = {
                        attribute: false,
                        display: true,
                        length: true,
                        initial: false,
                        max: false,
                        stepLength: false,
                        recyclable: false,
                        order: true,
                        state: true
                    };
                    if (that.dialog_Rule.state === '新增') {
                        that.dialog_Rule.form.data.display = 'yyyyMMddHHmmss'; // 显示格式默认值
                        that.dialog_Rule.form.data.length = 14; // 长度默认为14
                    }
                    break;
                case '3': // 当前机构
                    that.dialog_Rule.form.show = {
                        attribute: false,
                        display: false,
                        length: false,
                        initial: false,
                        max: false,
                        stepLength: false,
                        recyclable: false,
                        order: true,
                        state: true
                    };
                    break;
                case '4': // 对象属性（字段名）
                    that.dialog_Rule.form.show = {
                        attribute: true,
                        display: false,
                        length: true,
                        initial: false,
                        max: false,
                        stepLength: false,
                        recyclable: false,
                        order: true,
                        state: true
                    };
                    if (that.dialog_Rule.state === '新增') {
                        that.dialog_Rule.form.data.length = ''; // 长度
                        that.dialog_Rule.form.data.attribute = ''; // 值
                    }
                    break;
                case '5': // 流水号
                    that.dialog_Rule.form.show = {
                        attribute: false,
                        display: false,
                        length: true,
                        initial: true,
                        max: true,
                        stepLength: true,
                        recyclable: true,
                        order: true,
                        state: true
                    };
                    if (that.dialog_Rule.state === '新增') {
                        that.dialog_Rule.form.data.initial = 1; // 初始值默认为1
                        that.dialog_Rule.form.data.max = 10000; // 最大值默认为10000
                        that.dialog_Rule.form.data.length = 5; // 长度默认为5
                        that.dialog_Rule.form.data.stepLength = 1; // 步长默认为1
                        that.dialog_Rule.form.data.recyclable = '1'; // 是否可循环默认为是
                    }
                    break;
                default:
                    that.dialog_Rule.form.show = {
                        attribute: false,
                        display: false,
                        length: false,
                        initial: false,
                        max: false,
                        stepLength: false,
                        recyclable: false,
                        order: false,
                        state: false
                    };
            }
        },
        exit () {
            let that = this;
            that.$emit('exit', false);
        },
        displayQS (queryString, cb) {
            cb(this.dateDisplay);
        },
        displayQSSelect (item) {
            let that = this;
            that.dialog_Rule.form.data.length = item.length;
        },
        getDataTableName () {
            let that = this;
            if (/^[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+$/.test(that.builder.codeName)) {
                let tableName = that.builder.codeName.split('.')[0]; // 获取表名
                that.axios.get('pass/v1/mdtables/queryAllByBlurTableName')
                    .then(function (res) {
                        if (res.code === '0') {
                            for (let i = 0; i < res.data.length; i++) {
                                if (res.data[i].tableName === tableName) {
                                    that.getDataFields(res.data[i].tableId);
                                    break;
                                }
                            }
                        } else {
                            that.$message.error(res.message);
                        }
                    }).catch(function () {
                    });
            }
        },
        getDataFields (tableId) {
            let that = this;
            // 获取表中字段名
            that.axios.get('pass/v1/mdfields/getAllByTableId', {
                params: {
                    tableId: tableId
                }
            })
                .then(function (res) {
                    if (res.code === '0') {
                        let arr = [];
                        res.data.forEach(item => {
                            arr.push({
                                value: item.fieldName
                            });
                        });
                        that.tableFields = arr;
                    } else {
                        that.$message.error(res.message);
                    }
                }).catch(function () {
                });
        }
    }
}
</script>

<style lang="less" scoped>
.BusinessCodeRules {
    .title-box {
        overflow: hidden;
        border-bottom: 1px solid #e4e7ed;
        padding: 0 10px;
    }
    .BusinessCodeRules-box {
        margin: 0 10px;
        padding: 5px;
        // border: 1px solid #e4e7ed;
        .box {
            margin: 10px auto 0;
        }
        .box-button {
            text-align: right;
            .button {
                margin: 0 5px;
            }
        }
        .red {
            color: red;
        }
        .chartreuse {
            color: #1a9f17;
        }
    }
    .BusinessCodeRules-width-100 {
        width: 100%;
    }
    .dialogRule-box {
        margin-top: 20px;
        padding-bottom: 10px;
        border-top: 1px solid #e4e7ed;
        -webkit-box-shadow: 0 -5px 5px -5px #ccc;
        box-shadow: 0 -5px 5px -5px #ccc;
        .edit-flag {
            text-align: left;
            .span-text {
                display: inline-block;
                height: 26px;
                line-height: 26px;
                font-size: 14px;
                padding: 0 10px;
                border-left: 3px solid #70baf2;
                margin-bottom: 5px;
            }
        }
    }
    .editor-box {
        position: relative;
        // padding-right: 160px;
        .editor-but {
            // position: absolute;
            // width: 160px;
            top: 0;
            right: 0;
            text-align: right;
        }
    }
}
</style>
<style lang="less">
.my-autocomplete {
    li {
        line-height: normal;
        padding: 7px;
        .name {
            text-overflow: ellipsis;
            overflow: hidden;
        }
        .addr {
            font-size: 12px;
            color: #b4b4b4;
        }
        .highlighted .addr {
            color: #ddd;
        }
    }
}
// .my-autocomplete {
//     li {
//         line-height: normal;
//         height: 40px;
//         .value {
//             font-size: 14px;
//         }
//         .addr {
//             font-size: 12px;
//             color: #b4b4b4;
//         }
//     }
// }
.el-input-number-text-left {
    .el-input__inner {
        text-align: left;
    }
}
</style>
