<template>
    <avue-crud :option="tableOption"
               :data="tableData"
               :table-loading="tableLoading"
               :page="page"
               ref="crud"
               width="290"
               @row-save="handleSave"
               @row-update="handleUpdate"
               @row-del="handleDel"
               @selection-change="handleSelectionChange"
               @refresh-change="handlerefreshChange"
               @size-change="handleSizeChange"
               @current-change="handleCurrentChange">
        <template slot="menuLeft">
            <tableTopBtns ref="tableTopBtns" @RefreshData="handleList" :api="className" :importApi="importApi" :selectedData="tableRow" :tableOption="tableOption" :tableData="tableData" :importFlag="importFlag" :importStencil="importStencil" :parentRefs="$refs.crud" :excelName="'表配置Excel'" :pngName="'表配置PNG'" :dateFormat="['dateCreated']"/>
        </template>
        <template slot-scope="scope"
                  v-for="item in tableOption.column"
                  :slot="item.prop">
            <slot :row="scope.row"
                  :name="item.prop+'Column'"
                  v-if="item.slot"></slot>
        </template>
    </avue-crud>
</template>

<script>
    import tableTopBtns from './tableTopBtns';
    // import { validatenull } from '@/util/validate';
    import { isNumber } from '../util/util';
    export default {
        name: "single-table-page",
        props:{
            className: {//表
                type: String,
                required: true,
                default: () => {
                    return '';
                }
            },
            datetimeType:{//时间日期转换格式
                type: Object,
                default: () => {
                    return {};
                }
            },
            columnFunction : Function,//column自定义
            pageFlag:{//是否分页
                type: Boolean,
                default: () => {
                    return true;
                }
            },
            importApi:{
                type: String,
                default: () => {
                    return 'common/batchInput';
                }
            },
            importStencil:{
                type: Array,
                default: () => {
                    return [];
                }
            }
        },
        data () {
            return{
                classId:'',
                tableOption: {
                    border: true,
                    index: true,
                    indexLabel: '序号',
                    selection: true,
                    dialogWidth:'60%',
                    formWidth:'95%',
                    labelWidth: '110',
                    page:this.pageFlag,
                    column:[]
                }, //表格设置属性
                tableData: [], //表格的数据
                tableRow: [],
                tablePage: 1,
                tableLoading: false,
                tabelObj: {},
                page: {
                    total: 0, //总页数
                    currentPage: 1, //当前页数
                    pageSize: 10 //每页显示多少条
                },
                importFlag:true,
                dicNum:0
            }
        },
        watch: {
            className:{
                handler(newName, oldName) {
                    if(oldName !=='') this.initPage();
                },
                deep: true
            }
        },
        components: {
            tableTopBtns
        },
        created () {
            this.initPage();
        },
        methods:{
            initPage(){
                this.getData('importClass').then(res=>{
                    let data=res.data;
                    if(data.data.length!==0){
                        data.data.forEach(item=>{
                            if(this.className===item.className){
                                this.classId=item.id
                            }
                        });
                        if(this.classId !==''){
                            this.handleOption((column)=>{
                                const callack = () => {
                                    this.tableOption.column=Object.assign([],column);
                                };
                                if (typeof this.columnFunction === 'function') this.columnFunction(callack, column);
                                else callack();
                                this.handleList();
                                // this.$refs.crud.init();
                            })
                        }
                    }
                });
            },
            
            handleOption(callback){
                let _this=this;
                let x=function (column,item,index) {
                    return new Promise(resolve => {
                        _this.requestMethod('importColumnDictionary/queryDictionaryByColumnId',{columnId:item.id}).then(res=>{
                            let data=res.data;
                            if(item.dictionType==='1'){
                                column[index].dicData=data.data.dicrionary ? JSON.parse(data.data.dicrionary) : [];
                            }
                            else{
                                column[index].dicUrl=data.data.dicrionary || '';
                                // column[index].dicData=item.columnName;
                                column[index].props={
                                    label:data.data.showVal,
                                    value:data.data.saveVal
                                }
                            }
                            resolve();
                        });
                    })
                }
                let y=async function (data) {
                    let column=[]
                    for(let index = 0; index < data.data.length; index++){
                        let item=data.data[index];
                        column.push({
                            label: item.columnChn,
                            prop: item.columnName,
                            type: item.columnType,
                            rules: [{
                                required: item.required ==='true',
                                message: "不可为空",
                                trigger: "blur"
                            }],
                            valueDefault: isNumber(item.defaultVal) ? parseFloat(item.defaultVal):item.defaultVal,
                            placeholder: item.notice,
                            multiple: item.isMultiSelect ==='true',
                            disabled: item.isEnable ==='true',
                            span:item.inputSize,
                            overHidden:true,
                            width:item.thWidth,
                            fixed:item.isFixed === 'true',
                            filterable:item.isLike === 'true',
                            // hide:item.isShow === 'true',
                            slot:item.diy==='true',
                        });
                        if(item.isShow==='false') column[index].hide=false;
                        if(_this.datetimeType[item.columnName]){
                            column[index].valueFormat=_this.datetimeType[item.columnName].valueFormat;
                            column[index].format=_this.datetimeType[item.columnName].format;
                        }
                        if(item.subColumn !==null && item.subColumn!=='[]'){
                            column[index].cascaderItem=JSON.parse(item.subColumn);
                            column[index].cascaderChange=true;
                        }
                        if(index>0 && column[index-1].cascaderChange){
                            column[index].dicFlag=false;
                        }
                        if(item.dictionType !== '0'){
                            await x(column,item,index);
                        }
                    }
                    return column;
                }
                this.requestMethod('importColumn/queryColumns',{classId : this.classId}).then(res=>{
                    let data=res.data;
                    if(data.data){
                        y(data).then((column)=>{
                            callback(column);
                        });
                    }
                })
            },
            /**
             * @title 获取数据
             * @detail 赋值为tableData表格即可
             *
             **/
            handleList () {
                this.tableLoading = true;
                this.getData(this.className,Object.assign({},{pageNo:this.page.currentPage,pageSize:this.page.pageSize})).then(res => {
                    let data=res.data;
                    if(this.pageFlag){
                        this.tableData = data.data.data ? data.data.data : [];
                        this.page.total = data.data.total;
                    }
                    else {
                        this.tableData = data.data ? data.data : [];
                    }
                    if(this.dicNum!==0){
                        this.$refs.crud.dicInit();
                    }
                    else {
                        this.dicNum++;
                    }
                    // for(let item of this.tableOption.column){
                    //     if(item.type ==='select' || item.type==='tree' || item.type ==='checkbox' ){
                    //         if(item.multiple === true){
                    //             for(let items of this.tableData){
                    //                 items[item.prop]=items[item.prop] ? items[item.prop].split(',').map(Number) :[];
                    //             }
                    //         }
                    //     }
                    // }
                    this.tableLoading = false;
                }).catch(err => {
                    this.tableLoading = false;
                    this.$message.error(err.message ? err.message : '数据请求失败，请刷新重试！');
                });
            },
            /**
             * @title 当前选中的数据
             * @param val 选中的值
             *
             **/
            handleSelectionChange (val) {
                this.tableRow = val;
            },
            /**
             * @title 选中第几行
             * @param row 选中那几行数据
             * @detail 调用crud的toggleSelection方法即可
             *
             **/
            toggleSelection (row) {
                this.$refs.crud.toggleSelection(row);
            },
            /**
             * @title 数据添加
             * @param row 为当前的数据
             * @param done 为表单关闭函数
             *
             **/
            handleSave (row, done) {
                if(row.id){
                    this.$delete(row,'id')
                }
                this.saveData(this.className,row).then(()=>{
                    this.handleList();
                    this.$message({
                        showClose: true,
                        message: "添加成功",
                        type: "success"
                    });
                    done();
                }).catch(err => {
                    this.$message.error(err.message ? err.message : '数据请求失败，请刷新重试！');
                });
            },
            /**
             * @title 刷新数据
             *
             **/
            handlerefreshChange () {
                this.handleList(this.tableSearch);
                this.$notify({
                    message: `刷新数据成功`,
                    type: 'success',
                });
            },
            /**
             * @title 数据删除
             * @param row 为当前的数据
             * @param index 为当前更新数据的行数
             *
             **/
            handleDel (row, index) {
                this.$confirm(`是否确认删除序号为${index+1}`, "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        this.delData(this.className,row.id).then(()=>{
                            this.handleList();
                            this.$message({
                                showClose: true,
                                message: "删除成功",
                                type: "success"
                            });
                        }).catch(err => {
                            this.$message.error(err.message ? err.message : '数据请求失败，请刷新重试！');
                        });
                    })
                    .catch(err => { 
                        console.log(err)
                        this.$message.error(err)
                    });
            },
            /**
             * @title 数据更新
             * @param row 为当前的数据
             * @param index 为当前更新数据的行数
             * @param done 为表单关闭函数
             *
             **/
            handleUpdate (row, index, done) {
                this.saveData(this.className,row).then(()=>{
                    this.handleList();
                    this.$message({
                        showClose: true,
                        message: "修改成功",
                        type: "success"
                    });
                    done();
                }).catch(err => {
                    this.$message.error(err.message ? err.message : '数据请求失败，请刷新重试！');
                });
            },
            handleSizeChange(val) {//pageSize 改变
                this.page.pageSize=val;
                this.handleList();
            },
            handleCurrentChange(val) {//currentPage 改变
                this.page.currentPage=val
                this.handleList();
            }
        }
    }
</script>

<style scoped>

</style>