<template>
    <div class="dhc-tableSelect">
        <a-popover class="dhc-tableSelect-popover" ref="popover" :disabled="this.inputAttr.disabled"
            v-model:visible="visiable" placement="bottom" width="500" height="300" trigger="click">
            <template #content>
                <!-- <div class="dhc-tableSelect-popoverConent" v-clickoutside="() => { visiable = false }"> -->
                <!-- 搜索框 -->
                <div calss="dhc-tableSelect-search" :style="{ display: 'flex' }">
                    <a-select v-model.trim="selectValue" style="background-color: #f5f7fa;" placeholder="请选择"
                        :popper-append-to-body="false">
                        <a-select-option v-for="(item, index) in searchOptions" :key="index"
                            :value="item.selectValue ? item.selectValue : item.dataIndex">
                            {{ item.label }}</a-select-option>
                    </a-select>
                    <a-input v-if="searchEl == 'input'" v-model="searchValue" type="text" clearable
                        placeholder="请输入内容" />
                    <pro-select v-else v-model.trim="searchValue" style="width: 100%;" clearable placeholder="请选择"
                        :popper-append-to-body="false" v-bind="searchProps" />
                    <!-- 查询按钮 -->
                    <a-button style="background-color: #f5f7fa;" @click="handlerSearchClick">
                        <template #icon>
                            <SearchOutlined />
                        </template>
                    </a-button>
                </div>
                <!-- 单选表格 -->
                <a-table class="dhc-tableSelect-table" v-if="!isSelection" ref="table"
                    :dataSource="tableDataSource ? tableDataSource : []" size="small" max-height="250"
                    :style="{ ...tableStyle }" v-bind="tableOriginAttr" highlight-current-row
                    @row-click="handleCurrentChange">
                    <a-table-column v-for="(item, index) in trColumns" :key="index" :dataIndex="item.prop"
                        :title="item.label" v-bind="item"></a-table-column>
                </a-table>
                <!-- 多选表格 -->
                <a-table class="dhc-tableSelect-table" v-else ref="table" :data="tableDataSource ? tableDataSource : []"
                    size="small" max-height="250" :style="{ ...tableStyle }" v-bind="tableOriginAttr"
                    @select-all="handleSelectionChange" @select="handleSelectionChange">
                    <a-table-column type="selection" width="55" :reserve-selection="true">
                    </a-table-column>
                    <a-table-column v-for="(item, index) in trColumns" :key="index" :dataIndex="item.prop"
                        :title="item.label" v-bind="item"></a-table-column>
                </a-table>
                <!-- 分页栏 -->
                <div class="dhc-tableSelect-table-pagination" v-if="pagination">
                    <a-pagination small align="center" @current-change="currentChange" :current-page.sync="pageIndex"
                        :page-size="pageSize" layout="total, prev, pager, next" :total="getTableDataTotal">
                    </a-pagination>
                </div>
                <!-- </div> -->
            </template>
            <!-- 展示输入框 -->
            <a-input :value="inputValue" v-bind="inputAttr" clearable @clear="clear" suffix-icon="a-icon-search"
                placeholder="请选择"></a-input>
        </a-popover>

    </div>
</template>

<script>
import request from '@/utils/request'
import settings from '@/settings';
import { amtFormatter } from '@/utils/util.ts'
import { isEmpty, removeComma } from '@/utils/validate.js'
import { deepClone } from '@/utils/util.ts';
import { SearchOutlined } from '@ant-design/icons-vue';
const { systemPrefix } = settings
export default {
    name: 'TableSelect',
    model: {
        prop: 'value',
        event: 'inputChange'
    },
    components: {
        SearchOutlined,
    },
    props: {
        dataSource: Array,
        sqlId: String,
        inputAttr: {
            type: Object,
            default: function () {
                return {
                    disabled: false
                }
            }
        },
        tableAttr: {
            type: Object,
            required: true
        },
        value: [String, Array],
        lableKey: {
            type: String,
            required: true
        },
        valueKey: {
            type: String,
            required: true
        },
        //发送动态请求时传递的参数
        sqlParam: {
            type: Object,
            default: () => ({})
        },
        //若查询数据为一条数据，是否设置自动选中
        autoSelected: {
            type: Boolean,
            default: () => false
        },
        //回显时是否获取全部响应的数据
        getAllData: {
            type: Boolean,
            default: () => false
        },
        //用户自定义输入框方法
        cunstomInputContent: {
            type: Function
        }
    },
    data () {
        let {
            columns,
            style,
            isSelection = false,
            pageSize = '5',
            pagination = true,
            ...others
        } = this.tableAttr
        //获取要展示在搜索下拉框的列信息
        let searchOptions = columns.filter(item => item.issearch)
        //获取要展示的列信息
        let trColumns = columns.filter(col => col.visable === true || col.visable === undefined);
        let selectValue = searchOptions.length > 0 ? (searchOptions[0].selectValue ? searchOptions[0].selectValue : searchOptions[0].prop) : ''
        let searchEl = 'input'
        let searchProps = {}
        if (selectValue && searchOptions[0].searchProps) {
            let { el, props } = searchOptions[0].searchProps
            if (el) {
                searchEl = el
                searchProps = props ?? {}
            }
        }
        return {
            selectValue, //下拉框的值
            searchValue: '', //查询输入框值
            tableData: [], //表格数据源
            originTableData: [], //表格数据源备份数据
            trColumns: trColumns, //表格列配置参数(展示)
            columns, //表格列配置参数
            tableOriginAttr: others, //表格组件原生参数
            tableStyle: style, //表格样式
            currentRows: this.value, //当前选择的行
            currentRowAll: [], //选择行完整数据
            isSelection, //是否多选
            pageSize, //每页条数
            pageIndex: 1, //当前展示的页码
            searchOptions, //搜索下拉框设置信息
            pagination, //是否展示分页
            tableDataTotal: 0,
            visiable: false,
            translateFlag: false, //首次反显标志
            searchEl, //查询组件类型
            searchProps,  //查询组件属性
        };
    },
    methods: {
        //表格单选当前数据改变时的回调
        handleCurrentChange (currentRow, oldCurrentRow) {
            //设置翻译标志为已翻译，防止新增方法中触发返显方法
            this.translateFlag = true
            let that = this;
            //深拷贝一份,防止去除三位一逗后放大镜的表格中数据也被去除
            let currentRowtemp = JSON.parse(JSON.stringify(currentRow))
            let columnsTemp = JSON.parse(JSON.stringify(this.columns))

            //去除选中行的所有字段的三位一逗，
            columnsTemp.forEach(item => {
                if (item.formatterValue) {
                    let { type, prefix = '', suffix = '' } = item.formatterValue
                    if (type) {
                        switch (type) {
                            //金额，三位一逗
                            case 'amt': currentRowtemp[item.prop] = removeComma(currentRowtemp[item.prop])
                        }
                    }
                    currentRowtemp[item.prop] = currentRowtemp[item.prop].slice(prefix.length, currentRowtemp[item.prop].length - suffix.length)
                }
            })

            if (currentRowtemp[this.valueKey]) {
                this.currentRows = currentRowtemp[this.valueKey]
                this.currentRowAll = [currentRowtemp]
            }
            //更新放大镜input的值
            this.$emit("inputChange", this.currentRows)

            let updataForm = {};
            columnsTemp.forEach(item => {
                if (item.isbind && item.bindname != that.lableKey) {
                    updataForm[item.bindname] = currentRowtemp[item.prop]
                }

            })
            //更新表单其他输入框的值
            if (this.getAllData) {
                updataForm = { ...currentRowtemp, ...updataForm }
            }

            this.$emit('update:form', updataForm)
            //单选点击后关闭表格
            this.visiable = false
        },
        //表格多选数据变化时的回调
        handleSelectionChange (rows, row) {
            //设置翻译标志为已翻译，防止新增方法中触发返显方法
            this.translateFlag = true

            //深拷贝一份,防止去除三位一逗后放大镜的表格中数据也被去除
            let columnsTemp = JSON.parse(JSON.stringify(this.columns))
            let rowsTemp = JSON.parse(JSON.stringify(rows))
            let that = this;

            //去除选中行的所有字段的三位一逗，
            rowsTemp.forEach(rowItem => {
                columnsTemp.forEach(item => {
                    if (item.formatterValue) {
                        let { type, prefix = '', suffix = '' } = item.formatterValue
                        if (type) {
                            switch (type) {
                                //金额，三位一逗
                                case 'amt': rowItem[item.prop] = removeComma(rowItem[item.prop])
                            }
                        }
                        rowItem[item.prop] = rowItem[item.prop].slice(prefix.length, rowItem[item.prop].length - suffix.length)
                    }
                })
            })
            this.currentRows = rowsTemp.map(item => item[that.valueKey])
            this.currentRowAll = rowsTemp
            //更新放大镜input的值
            this.$emit("inputChange", this.currentRows)

            let updataForm = {};
            this.columns.forEach(item => {
                if (item.isbind && item.bindname != that.lableKey) {
                    updataForm[item.bindname] = rowsTemp.map(attr => {
                        return attr[item.prop]
                    })
                }
            })
            //更新表单其他输入框的值
            this.$emit('update:form', updataForm)
        },
        //搜索按钮回调
        handlerSearchClick () {
            if (!this.sqlId) {
                if (this.searchValue != '') {
                    this.tableData = this.originTableData.filter(item => item[this.selectValue].indexOf(this.searchValue) > -1)
                } else {
                    this.tableData = this.originTableData;
                }
            } else {
                if (this.searchValue != '') {
                    const {
                        pageSize
                    } = this;
                    this.pageIndex = 1
                    let p = {
                        pageIndex: 1,
                        pageSize
                    };
                    this.loadApiData(p)
                } else {
                    const {
                        pageSize
                    } = this;
                    this.pageIndex = 1
                    let p = {
                        pageIndex: 1,
                        pageSize,
                        currentRows: this.currentRows
                    };
                    this.tableData = this.loadApiData(p)
                }
            }
        },
        //分页改变时
        async currentChange (event) {
            if (!this.sqlId) {
                this.pageIndex = event
                this.tableRowSelectionOption()
            } else {
                const {
                    pageSize
                } = this;
                let p = {
                    pageIndex: event,
                    pageSize
                };
                await this.loadApiData(p)
                //设置表格选中选择列
                this.tableRowSelectionOption()
            }
        },
        //加载翻译数据
        async loadTranslateData (value) {
            const that = this;
            if (typeof value == "string") {
                //获取rowKey列信息
                let searchOptions = that.columns.filter(item => item.prop == that.tableAttr.rowKey)
                let selectValue = searchOptions ? (searchOptions[0].selectValue ? searchOptions[0].selectValue : searchOptions[0].prop) : ''
                let resp = await request(systemPrefix + '/sys/common/customQuery', {
                    method: 'POST',
                    data: {
                        sqlId: that.sqlId,
                        sqlParam: {
                            searchValue: value,
                            selectValue: selectValue,
                            ...that.sqlParam,
                        }
                    },
                    requestType: 'json',
                });
                //单选情况使用find来查找，有问题再改回来
                //that.currentRowAll = resp.data.filter(item => item[this.valueKey] == value)
                that.currentRowAll = []
                let row = resp.data.find(item => item[that.valueKey] == value)
                if (row == undefined) {
                    console.warn("%c 放大镜组件", 'color: blue;', "未找到对应的翻译数据,请检查valueKey配置是否正确!")
                }
                resp.data?.length > 0 && that.currentRowAll.push(row)
                //设置表格选中选择列
                this.tableRowSelectionOption()
            } else if (value instanceof Array) {
                //获取rowKey列信息
                let searchOptions = that.columns.filter(item => item.prop == that.tableAttr.rowKey)
                let selectValue = searchOptions ? (searchOptions[0].selectValue ? searchOptions[0].selectValue : searchOptions[0].prop) : ''
                //回显之前置空
                this.currentRowAll = []
                //遍历要返显的值
                value.forEach(async (item) => {
                    let resp = await request(systemPrefix + '/sys/common/customQuery', {
                        method: 'POST',
                        data: {
                            sqlId: that.sqlId,
                            sqlParam: {
                                searchValue: item,
                                selectValue: selectValue,
                                ...that.sqlParam,
                            }
                        },
                        requestType: 'json',
                    });
                    resp.data?.length > 0 && this.currentRowAll.push(resp.data[0])
                    //把该条数据改为选中状态
                    this.$refs.table.toggleRowSelection(resp.data[0], true);
                })
                //设置表格选中选择列
                // this.tableRowSelectionOption()
            }
        },
        //加载api数据
        async loadApiData (Param) {
            const that = this;
            const {
                pageIndex,
                pageSize
            } = Param;
            let resp = await request(systemPrefix + '/sys/common/customQuery', {
                method: 'POST',
                data: {
                    pageIndex: pageIndex,
                    pageSize: pageSize,
                    sqlId: that.sqlId,
                    sqlParam: {
                        searchValue: that.searchValue,
                        selectValue: that.selectValue,
                        ...that.sqlParam,
                    }
                },
                requestType: 'json',
            });
            //设置自动选中
            if (!this.visiable && this.autoSelected && resp.data?.length === 1) {
                let updataForm = {};
                this.columns.forEach(item => {
                    if (item.isbind && item.bindname != that.lableKey) {
                        updataForm[item.bindname] = resp.data[0][item.bindname]
                    }
                })
                this.currentRows = resp.data[0][this.valueKey]
                //更新放大镜input的值
                this.$emit("inputChange", this.currentRows)
                if (this.getAllData) {
                    updataForm = { ...resp.data[0], ...updataForm }
                }
                this.$emit('update:form', updataForm)
            }


            //对响应数据设置三位一逗
            that.formatColums(resp.data)

            this.tableData = resp.data;
            this.tableDataTotal = resp.totalCount


        },
        //设置表格选中选择列
        tableRowSelectionOption () {
            let that = this
            if (this.isSelection) { //多选
                let rows = [];
                if (this.currentRowAll instanceof Array) {
                    this.currentRowAll.forEach(attr => {
                        this.tableData.filter(item => {
                            if (item[that.valueKey] == attr?.[that.valueKey]) {
                                rows.push(item)
                            }
                        })
                    })
                    rows.forEach(row => {
                        this.$refs.table.toggleRowSelection(row, true);
                    });
                }
            } else { //单选
                let row = {};
                this.tableData?.forEach(item => {
                    if (that.currentRowAll.length > 0 && item[that.valueKey] == that.currentRowAll[0]?.[that.valueKey]) {
                        row = item;
                    }
                })
                this.$refs.table.setCurrentRow(row);
                //更新表单其他输入框的值
                if (row != undefined && row != null && Object.keys(row).length != 0) {
                    let updataForm = {};
                    this.columns.forEach(item => {
                        if (item.isbind && item.bindname != this.lableKey) {
                            updataForm[item.bindname] = row[item.prop]
                        }
                    })
                    if (this.getAllData) {
                        updataForm = { ...row, ...updataForm }
                    }
                    this.$emit('update:form', updataForm)
                }
            }
        },
        /**
         * 展示输入框清空按钮回调
         */
        clear () {
            this.currentRowAll = []
            //更新放大镜input的值
            this.$emit("inputChange", "")
            //更新表单其他输入框的值
            this.$emit('update:form', {})
            this.$refs.table?.toggleRowSelection({}, false);
            this.$refs.table?.setCurrentRow();
        },
        /**
         * 设置三位一逗
         *
         * */
        formatColums (data) {
            let that = this
            let columns = that.tableAttr.columns
            //格式化表格列数据
            if (columns.length > 0) {
                for (let i = 0; i < data?.length; i++) {
                    columns.forEach((item, index) => {
                        if (item.formatterValue) {
                            let { type, prefix = '', suffix = '' } = item.formatterValue
                            if (type) {
                                switch (type) {
                                    //金额，三位一逗
                                    case 'amt':
                                        data[i][item.prop] = amtFormatter(data[i][item.prop]);
                                }
                            }
                            data[i][item.prop] = prefix + data[i][item.prop] + suffix
                        }
                    })
                }
            }
        }
    },
    watch: {
        value: {
            immediate: true,
            handler (val, oldVal) {
                //触发change事件
                this.$emit('change', deepClone(this.currentRowAll))
                if (val != undefined && val !== '') {
                    if (!this.translateFlag) {
                        //加载翻译数据
                        this.translateFlag = true
                        this.loadTranslateData(val)
                    }
                } else {
                    this.clear()
                }
            }
        },
        //监视计算属性
        sqlParamTemp: {
            immediate: true,
            deep: true,
            async handler (val, oldVal) {
                if (oldVal !== undefined) {
                    if (JSON.stringify(val) == JSON.stringify(oldVal)) {
                        return;
                    }
                    //设置表格数据源
                    if (this.sqlId) { //api数据源
                        const {
                            pageIndex,
                            pageSize
                        } = this;
                        let p = {
                            pageIndex,
                            pageSize
                        };
                        await this.loadApiData(p)
                        await this.loadTranslateData(this.value)
                    }
                    //设置表格选中选择列
                    this.tableRowSelectionOption();
                }
            }
        },
        selectValue (value, oldValue) {
            if (value != oldValue) {
                let searchOptions = this.columns.filter(item => item.prop == value || item.selectValue == value)
                if (searchOptions.length > 0) {
                    if (searchOptions[0].searchProps && searchOptions[0].searchProps.el) {
                        this.searchEl = searchOptions[0].searchProps.el
                        this.searchProps = searchOptions[0].searchProps.props ?? {}
                        this.searchValue = ''
                    } else {
                        this.searchEl = "input"
                        this.searchValue = ''
                    }
                }
            }
        }
    },
    computed: {
        //分页栏总数
        total () {
            if (this.sqlId) {
                return this.tableDataTotal;
            } else {
                return this.tableData.length;
            }
        },
        //输入框的值
        inputValue () {
            let result = ""
            //多选
            // if(this.isSelection){
            let inputValues = []
            if (!this.currentRowAll) {
                return '';
            }
            //如何存在自定义输入框名称方法，则返回其方法的返回值
            if (!isEmpty(this.cunstomInputContent)) {
                return this.cunstomInputContent(this.currentRowAll)
            }
            this.currentRowAll.map(attr => {
                inputValues.push(attr?.[this.lableKey])
            })

            if (inputValues.length > 0) {
                result = inputValues.join(',');
            } else {
                result = this.currentRowAll.join(',');
            }

            if (result) {
                return result;
            } else {
                return this.value;
            }
        },
        //表格数据源
        tableDataSource () {
            const that = this;
            if (!this.sqlId) {
                return this.tableData.slice((that.pageIndex - 1) * that.pageSize, that.pageIndex * that.pageSize);
            } else {
                return this.tableData;
            }
        },
        getTableDataTotal () {
            if (!this.sqlId) {
                return this.tableData.length;
            } else {
                return this.tableDataTotal;
            }
        },
        //解决深度监视sqlParam但是val和oldVal是同一个对象的问题
        //添加计算属性，通过监视此计算属性来达到深度监视是否改变
        sqlParamTemp () {
            return JSON.parse(JSON.stringify(this.sqlParam))
        }
    },
    async mounted () {
        let that = this
        //设置表格数据源
        //本地数据源
        if (this.dataSource) {
            this.tableData = this.dataSource;
            //存储数据源源数据，供搜索使用
            this.originTableData = this.tableData;
            this.tableDataTotal = this.tableData.length;
            let currentRowAll = [];
            if (this.currentRows instanceof Array) {
                this.currentRows.forEach(item => {
                    that.dataSource.forEach(attr => {
                        if (item == attr[this.valueKey]) {
                            currentRowAll.push(attr)
                        }
                    })
                })
            } else {
                this.dataSource.forEach(attr => {
                    if (that.currentRows == attr[this.valueKey]) {
                        currentRowAll.push(attr)
                    }
                })
            }
            if (this.currentRows && currentRowAll.length == 0) {
                if (this.currentRows instanceof Array) {
                    this.currentRows.forEach(item => {
                        currentRowAll.push({
                            [that.valueKey]: item,
                            [that.lableKey]: item
                        })
                    })
                } else {
                    currentRowAll = {
                        [that.valueKey]: this.currentRows,
                        [that.lableKey]: this.currentRows
                    }
                }

            }
            this.currentRowAll = currentRowAll;
        } else if (this.sqlId) { //api数据源
            const {
                pageIndex,
                pageSize
            } = this;
            let p = {
                pageIndex,
                pageSize
            };
            await this.loadApiData(p)
            //加载翻译数据
            // await this.loadTranslateData()
        }
        //设置表格选中选择列
        // this.tableRowSelectionOption();
    },


};
</script>

<style lang="scss">
.dhc-tableSelect-popoverConent .a-input__validateIcon {
    display: none;
}
</style>
