<template>
    <div class="search-pack">
        <div class="ele-pack">
            <el-select class="field-select" v-model="currentField.fieldName" @change="fieldChange" size="mini" placeholder="请选择字段">
                <el-option
                    v-for="item in fields"
                    :key="item.fieldCode"
                    :label="item.fieldName"
                    :value="item.fieldCode">
                </el-option>
            </el-select>
            <el-select class="rule-select" v-model="currentRule.code" @change="ruleChange" size="mini" placeholder="请选择规则">
                <el-option
                    v-for="item in currentField.operations"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code">
                </el-option>
            </el-select>
            <el-input @keyup.enter.native='searchClick' v-if="currentField.fieldType === 'STRING' || currentField.fieldType === 'FIELD' || currentField.fieldType === undefined" v-model="currentValue.value" size="mini" placeholder="请输入内容"></el-input>
            <el-input-number @keyup.enter.native='searchClick' v-if="currentField.fieldType === 'NUMBER'" v-model="currentValue.value" size="mini" label="请输入内容"></el-input-number>
            <el-date-picker
                :editable="false"
                v-show="currentField.fieldType === 'DATE' && this.currentRule.code !== 'BETWEEN'"
                v-model="currentValue.value"
                type="datetime"
                size="mini"
                placeholder="请选择时间"
                :clearable="false">
            </el-date-picker>
            <el-date-picker
                size="mini"
                style="width: 320px"
                :editable="false"
                v-show="currentField.fieldType === 'DATE' && this.currentRule.code === 'BETWEEN'"
                v-model="currentValue.value"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                placeholder="请选择时间范围"
                :clearable="false">
            </el-date-picker>

            <el-input @keyup.enter.native='searchClick' v-if="currentField.fieldType === 'DICT'" :value="currentValue.name" @focus="dictInputClick" size="mini" suffix-icon="el-icon-s-order" placeholder="请选择内容"></el-input>
            <el-select v-if="currentField.fieldType === 'ENUM'" v-model="currentValue.value" size="mini" placeholder="请选择一项">
                <el-option
                    v-for="item in currentField.enumList"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code">
                </el-option>
            </el-select>


            <el-button @click="searchClick" type="primary" plain size="mini">搜索</el-button>
            <el-button @click="resetClick" class="reset" size="mini">重置</el-button>
            <el-popover
                placement="bottom"
                width="400"
                trigger="hover">
                <el-table :data="selectedFieldList" border empty-text="暂无已选择条件">
                    <el-table-column width="338" property="date" label="已筛选条件" align="left">
                        <template slot-scope="scope">
                            <div>
                                {{scope.row.field.fieldName + ' - ' + scope.row.rule.name + ' - ' + scope.row.value.name}}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column width="60" property="name" label="操作" align="center">
                        <template slot-scope="scope">
                            <el-button type="text" @click="removeSelectedFieldClick(scope.row, scope.$index)">移除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-button size="mini" slot="reference">已筛选条件（
                    <span style="font-weight: bold; color: red">{{selectedFieldList.length}}条</span>
                    ）</el-button>
            </el-popover>
        </div>


        <!-- 字典弹框 -->
        <el-dialog
            title="数据列表"
            :visible.sync="dictDialog"
            :show-close="false"
            :close-on-press-escape="false"
            :close-on-click-modal="false"
            width="400px">
            <div class="dict-table-pack">
                <el-table
                    ref="dictTable"
                    border
                    highlight-current-row
                    @current-change="dictCurrentChange"
                    tooltip-effect="dark"
                    style="width: 100%"
                    :height="380"
                    :data="dictDataList">
                    <el-table-column
                        align="center"
                        show-overflow-tooltip
                        v-for="(item, index) in dictFieldList"
                        :key="index"
                        :prop="item.fieldCode"
                        :label="item.fieldName">
                    </el-table-column>
                </el-table>
            </div>
            <span slot="footer" class="dialog-footer text-center">
                <el-button size="mini" type="primary" icon="el-icon-check" @click="confirmClick">确定</el-button>
                <el-button size="mini" icon="el-icon-close" @click="cancelClick">取消</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import request from '@/utils/request';
export default {
    name: 'Search',
    props: {
        // 查询数据的code
        searchCode: {
            type: String,
            required: true
        },
        // 查询字段是否是多选
        multiple: {
            type: Boolean,
            default: false
        }
    },
    data () {
        return {
            /* 状态逻辑 */
            statusList: [],              // 备选状态列表
            /* 字典逻辑 */
            dictDialog: false,           // 备选字典弹框
            dictKeyword: '',             // 备选字典的搜索关键字
            dictTotal: 0,                // 备选字典的总条数
            dictCurrentPage: 1,          // 备选字典的当前列表页
            dictPageSize: 50,            // 备选字典的当前列表数量
            dictPrimaryField: '',
            dictViewField: '',
            dictFieldList: [],           // 备选字典字段列表
            dictDataList: [],            // 备选字典数据列表
            dictSelectedData: '',        // 选中的字典列表
            /* 其他逻辑 */
            fields: [],
            field: {},  // 当前选中的字段
            rule: '',   // 当前选中的匹配规则
            value: '',   // 当前选中的值
            selectedFieldList: [],
            currentField: {},
            currentRule: {},
            currentValue: {}
        }
    },
    methods: {
        // 查询数据字段切换事件 -- 会根据字段类型影响value的类型变化
        fieldChange (v) {
            this.currentField = this.getObjectByList(v, this.fields);
            this.currentRule = {};
            this.currentValue = {};
        },
        ruleChange (v) {
            this.currentValue = {}
            if (this.currentField.operations && this.currentField.operations.length > 0) {
                this.currentField.operations.map(ruleItem => {
                    if (ruleItem.code === this.currentRule.code) {
                        this.currentRule.name = ruleItem.name
                    }
                })
            }
        },
        // 搜索按钮点击事件
        searchClick () {
            console.log(this.currentValue)
            // 1. 先判断是否可进行操作
            if (!this.currentField.hasOwnProperty('fieldCode') && JSON.stringify(this.currentRule) === '{}' && JSON.stringify(this.currentValue) === '{}') {
                let searchParam = {
                    searchCode: this.searchCode,
                    filters: []
                }
                this.$emit('reset', searchParam)
                return false
            } else if (this.currentField.fieldCode === undefined || this.field.fieldCode === null || JSON.stringify(this.currentRule) === '{}' || JSON.stringify(this.currentValue) === '{}') {
                this.$message.warning('搜索条件不完整！');
                return false
            }
            // 2. 根据类型，组织一下每项的key和name
            if (this.currentField.fieldType === 'ENUM') {
                if (this.currentField.enumList && this.currentField.enumList.length > 0) {
                    this.currentField.enumList.map(enumItem => {
                        if (enumItem.code === this.currentValue.value) {
                            this.currentValue.name = enumItem.name
                        }
                    })
                }
            } else if (this.currentField.fieldType === 'DICT') {
                console.info('DICT')
            } else {
                this.currentValue.name = this.currentValue.value;
            }
            // 3. 如果已筛选列表存在此条件要把原来的条件删除再追加
            this.selectedFieldList.map((item, index) => {
                if (item.field.fieldCode === this.currentField.fieldCode) {
                    this.selectedFieldList.splice(index, 1)
                }
            })
            // 4. 把数据再添加到已筛选列表
            this.selectedFieldList.unshift({
                field: _.cloneDeep(this.currentField),
                rule: _.cloneDeep(this.currentRule),
                value: _.cloneDeep(this.currentValue)
            })
            // 5. 并且返回页面需要的数据格式
            let list = [];
            this.selectedFieldList.map(item => {
                if (item.field.fieldType === 'DATE' && this.currentRule.code === 'BETWEEN') {
                    // 当字段为时间并且筛选规则为范围时
                    list.unshift({
                        fieldCode: item.field.fieldCode,
                        operation: item.rule.code,
                        value: [this.formatDate(item.value.value[0], 'yyyy-MM-dd hh:mm:ss'), this.formatDate(item.value.value[1], 'yyyy-MM-dd hh:mm:ss')]
                    })
                } else if (item.field.fieldType === 'DATE' && this.currentRule.code !== 'BETWEEN') {
                    // 当字段为时间并且筛选规则不为范围时
                    list.unshift({
                        fieldCode: item.field.fieldCode,
                        operation: item.rule.code,
                        value: this.formatDate(item.value.value, 'yyyy-MM-dd hh:mm:ss')
                    })
                } else {
                    list.unshift({
                        fieldCode: item.field.fieldCode,
                        operation: item.rule.code,
                        value: item.value.value
                    })
                }
            })
            let searchParam = {
                searchCode: this.searchCode,
                filters: _.cloneDeep(list)
            }
            console.info(searchParam)
            this.$emit('search', searchParam)
        },
        // 重置按钮点击事件
        resetClick () {
            this.selectedFieldList = [];
            this.currentField = {};
            this.currentRule = {};
            this.currentValue = {};
            let searchParam = {
                searchCode: this.searchCode,
                filters: []
            }
            this.$emit('reset', searchParam)
        },
        // 移除已选中条件
        removeSelectedFieldClick (row, index) {
            this.selectedFieldList.splice(index, 1)
            if (this.selectedFieldList.length > 0) {
                this.currentField = _.cloneDeep(this.selectedFieldList[0].field)
                this.currentRule = _.cloneDeep(this.selectedFieldList[0].rule)
                this.currentValue = _.cloneDeep(this.selectedFieldList[0].value)
            } else {
                this.currentField = {}
                this.currentRule = {}
                this.currentValue = {}
            }
            this.searchClick()
        },
        // 字典input点击事件
        dictInputClick () {
            this.dictDialog = true;
            this.dictKeyword = '';
            this.dictCurrentPage = 1;
            this.dictPageSize = 50;
            this.getDictList();
        },
        // 字典弹框 单选选中事件
        dictCurrentChange (row) {
            this.dictSelectedData = _.cloneDeep(row);
        },
        // 字典弹框 分页页数发生了变化
        onCurrentChange (page) {
            this.dictCurrentPage = page;
            this.getDictList();
        },
        // 字典弹框 分页分页数量发生了变化
        onSizeChange (size) {
            this.dictCurrentPage = 1;
            this.dictPageSize = size;
            this.getDictList();
        },

        // 字典弹框 确定点击事件
        confirmClick () {
            if (this.dictSelectedData !== '' && this.dictSelectedData !== null && this.dictSelectedData !== undefined) {
                this.dictDialog = false;
                this.currentValue = {
                    value: this.dictSelectedData[this.dictPrimaryField],
                    name: this.dictSelectedData[this.dictViewField]
                }
            } else {
                this.$message.warning('请选中一条数据！');
            }
        },
        // 字典弹框 取消点击事件
        cancelClick () {
            this.dictDialog = false;
        },
        // 根据key获取数组中对应的对象
        getObjectByList (value, list) {
            return _.cloneDeep(list.find((v, i) => {
                if (v.fieldCode === value) {
                    if (v.operations === undefined) {
                        v.operations = []
                    }
                    return v
                }
            }))
        },
        // 获取字典相关信息
        getDictList () {
            let param = {
                pageNum: this.dictCurrentPage,
                pageSize: this.dictPageSize,
                like: this.dictKeyword
            };
            if (this.currentField.url === undefined) {
                this.$message.warning('请告知管理员，缺少 url 字段！');
            } else {
                // 直接请求后端返回的接口，从接口中获取数据渲染col和row
                request({
                    url: `${process.env.API_HOST}${this.currentField.url}`,
                    method: 'get',
                    data: {
                        // tableName: this.field.tableName
                    }
                }).then(response => {
                    if (response.code === 600) {
                        console.info(response.data)
                        this.dictPrimaryField = response.data.primaryField;
                        this.dictViewField = response.data.viewField;
                        this.dictFieldList = _.cloneDeep(response.data.fields);
                        this.dictDataList = _.cloneDeep(response.data.values);
                    } else {
                        this.$message.warning('请求出错，请重新操作！');
                    }
                })
            }
        },
        // 处理日期时间格式
        formatDate (date, fmt) {
            let nowDate = new Date(date)
            let o = {
                'M+': nowDate.getMonth() + 1, //月份
                'd+': nowDate.getDate(), //日
                'h+': nowDate.getHours(), //小时
                'm+': nowDate.getMinutes(), //分
                's+': nowDate.getSeconds(), //秒
                'q+': Math.floor((nowDate.getMonth() + 3) / 3), //季度
                'S': nowDate.getMilliseconds() //毫秒
            }
            if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (nowDate.getFullYear() + '').substr(4 - RegExp.$1.length))
            for (let k in o) {
                if (new RegExp('(' + k + ')').test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
                }
            }
            return fmt
        }
    },
    mounted () {
        // 直接请求后端返回的接口，从接口中获取数据渲染col和row
        if (this.searchCode === undefined || this.searchCode === null) {
            this.$message.warning('请传入searchCode参数！');
        } else {
            request({
                url: `${process.env.API_HOST}/api/search/filterList`,
                method: 'get',
                data: {
                    searchCode: this.searchCode
                }
            }).then(response => {
                console.log(response.data)
                if (response.code === 600) {
                    this.fields = _.cloneDeep(response.data)
                } else {
                    this.$message.warning('请求出错，请重新操作！');
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
    .search-pack {
        text-align: right;

        .ele-pack {
            /deep/ .el-input {
                width: 200px;
            }
            /deep/ .el-textarea {
                width: 200px;
            }
            /deep/ .el-input-number--mini {
                width: 200px;
            }
            /deep/ .el-button {
                margin-left: 10px;
            }
            /deep/ .el-button+.el-button {
                margin-left: 5px;
            }

            .field-select, .rule-select {
                /deep/ .el-input {
                    width: 130px;
                }
                /deep/ .el-textarea {
                    width: 130px;
                }
                /deep/ .el-input-number--mini {
                    width: 130px;
                }
            }
        }

        .dict-search-pack {
            text-align: right;
        }
        .dict-table-pack {
            margin-top: 10px;
        }
        /deep/ .current-row {
            background-color: #b2d8ff!important;
        }
        /deep/ .el-table--striped .el-table__body tr.el-table__row--striped.current-row td, /deep/ .el-table__body tr.current-row>td, /deep/ .el-table__body tr.hover-row.current-row>td, /deep/ .el-table__body tr.hover-row.el-table__row--striped.current-row>td, /deep/ .el-table__body tr.hover-row.el-table__row--striped>td, /deep/ .el-table__body tr.hover-row>td {
            background-color: #b2d8ff!important;
        }
    }


</style>
