<template>
    <div style="margin:0 auto;width:100%">
        <div class="header">
            <el-form :model="tableSearch"
                     ref="tableSearch"
                     :inline="true">
                <el-form-item label="表名">
                    <el-select v-model="tableSearch.classId" @change="SearchChange">
                        <el-option
                                v-for="item in dicClassName"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
        </div>
        <avue-crud :option="tableOption"
                   :data="tableData"
                   :table-loading="tableLoading"
                   :page="page"
                   ref="crud"
                   width="290"
                   :before-open="beforeOpen"
                   :before-close="beforeClose"
                   @row-save="handleSave"
                   @row-update="handleUpdate"
                   @row-del="handleDel"
                   @selection-change="handleSelectionChange"
                   @refresh-change="handlerefreshChange"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange">
            <template slot="menuLeft">
                <el-button type="primary"
                           @click="rowAdd"
                           icon="el-icon-plus"
                           size="small">新 增</el-button>
                <tableTopBtns @RefreshData="handleList" api="importColumn" :selectedData="tableRow" :tableOption="tableOption" :tableData="tableData" :parentRefs="$refs.crud" :excelName="'字段配置Excel'" :pngName="'字段配置PNG'" :dateFormat="['dateCreated']"/>
            </template>
            <template slot="menu" slot-scope="scope">
                <el-button type="primary"
                           icon="el-icon-edit"
                           size="small"
                           @click.stop="rowEdit(scope.row,scope.index)">编 辑</el-button>
                <el-button type="danger"
                           icon="el-icon-delete"
                           size="small"
                           @click.stop="handleDel(scope.row,scope.index)">删 除</el-button>
            </template>
            <template slot="columnTypeForm" slot-scope="scope">
                <el-select v-model="scope.value" @change="handleChange">
                    <el-option
                            v-for="item in tableOption.dicData.CRUDTYPE"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                    </el-option>
                </el-select>
            </template>
            <template slot="dictionTypeForm" slot-scope="scope">
                <div>
                    <el-radio-group v-model.number="dicRadio">
                        <el-radio :label="1">选项</el-radio>
                        <el-radio :label="2">文本</el-radio>
                    </el-radio-group>
                    <el-form v-if="dicRadio===1"
                             class="dialog-dicData">
                        <el-button type="primary"
                                   @click="dicAdd"
                                   size="small"
                                   style="margin-bottom:15px">新增域名</el-button>
                        <el-form-item v-for="(item, index) in dicData.dicrionary"
                                      :key="index"
                                      class="item">
                            <div class="item-s">
                                <el-input v-model="item.label" placeholder="输入字典的label"></el-input>
                                <el-input v-model="item.value"
                                          placeholder="输入字典的value"></el-input>
                                <el-button @click.prevent="dicRemove(index)">删除</el-button>
                            </div>
                        </el-form-item>
                    </el-form>
                    <template v-else-if="dicRadio===2">
                        <div>
                            <el-form :model="dicText"  label-width="60px">
                                <el-form-item label="URL">
                                    <el-input v-model="dicText.dicrionary"
                                              placeholder="请输入字典名称"></el-input>
                                </el-form-item>
                                <div style="display:flex;">
                                    <el-form-item label="展示名">
                                        <el-input v-model="dicText.showVal"
                                                  placeholder="输入字典的展示名"></el-input>
                                    </el-form-item>
                                    <el-form-item label="保存名" style="margin-left: 10px;">
                                        <el-input v-model="dicText.saveVal"
                                                  placeholder="输入字典的保存名"></el-input>
                                    </el-form-item>
                                </div>
                            </el-form>
                        </div>
                    </template>
                </div>
            </template>
        </avue-crud>
    </div>
</template>

<script>
    import tableTopBtns from '../common/tableTopBtns';
    import getList from './const/index';
    import { validatenull } from '../util/validate';
    export default {
        name: "fieldConfiguration",
        components: {
            tableTopBtns
        },
        data () {
            return {
                dicClassName:[],
                tableOption: {}, //表格设置属性
                tableData: [], //表格的数据
                tableRow: [],
                tableSearch: {
                    classId:""
                },
                tablePage: 1,
                tableLoading: false,
                tabelObj: {},
                page: {
                    total: 0, //总页数
                    currentPage: 1, //当前页数
                    pageSize: 10 //每页显示多少条
                },
                grade: {
                    box: false,
                    check: []
                },
                dicRadio:1,
                dicData: {
                    dicrionary:[]
                },
                dicText:{
                    dicrionary:"",
                    showVal:"",
                    saveVal:""
                },
                propsURL:{},
                dicID:-1
            };
        },
        created () {
            this.tableOption={
                border: true,
                index: true,
                indexLabel: '序号',
                selection: true,
                labelWidth:'110',
                addBtn:false,
                editBtn:false,
                delBtn:false,
                dicData:{
                    className:[],
                    columnName:[],
                    subColumn:[],
                    CRUDTYPE:[{
                        label: "输入框",
                        value: 'text'
                    }, {
                        label: "选择框",
                        value: 'select'
                    }, {
                        label: "密码框",
                        value: 'password'
                    }, {
                        label: "树型框",
                        value: 'tree'
                    }, {
                        label: "富文本编辑框",
                        value: 'ueditor'
                    }, {
                        label: "多行文本框",
                        value: 'textarea'
                    }, {
                        label: "单选框",
                        value: 'radio'
                    }, {
                        label: "多选框",
                        value: 'checkbox'
                    }, {
                        label: "数字框",
                        value: 'number'
                    }, {
                        label: "日期框",
                        value: 'date'
                    }, {
                        label: "日期范围框",
                        value: 'daterange'
                    }, {
                        label: "时间范围框",
                        value: 'datetimerange'
                    }, {
                        label: "时间框",
                        value: 'datetime'
                    },{
                        label: "24小时框",
                        value: 'time'
                    }, {
                        label: "周",
                        value: 'week'
                    }, {
                        label: "月",
                        value: 'month'
                    }, {
                        label: "年",
                        value: 'year'
                    }, {
                        label: "滑动框",
                        value: 'silder'
                    }, {
                        label: "评价框",
                        value: 'rate'
                    }, {
                        label: "上传框",
                        value: 'upload'
                    },{
                        label: "表格查询框",
                        value: 'dynamicquery'
                    }]
                },
                column: getList('all')
            }
            this.getData('importClass').then(res=>{
                let data=res.data;
                let temp=[];
                data.data.forEach(item=>{
                    temp.push({
                        label: item.classNameChn,
                        className:item.className,
                        value: item.id,
                    })
                });
                this.dicClassName=temp;
                this.tableOption.column.forEach(item=>{
                    if(item.prop === 'className'){
                        item.dicData=temp;
                    }
                })
                if(temp.length!==0){
                    this.tableSearch={
                        classId:temp[0].value
                    };
                    this.dicDataChange();
                    this.handleList();
                }
            })
        },
        watch: { },
        mounted () { },
        computed: {
        },
        props: [],
        methods: {
            handleList () {//获取数据
                this.tableLoading = true;
                this.requestMethod('importColumn/queryColumns',{classId : this.tableSearch.classId,pageNo:this.page.currentPage,pageSize:this.page.pageSize}).then(res => {
                    let data=res.data;
                    if(data.code==="200"){
                        for(let item of data.data.data){
                            if(item.subColumn !==null ) item.subColumn=JSON.parse(item.subColumn);
                            else item.subColumn=[];
                        }
                        this.tableData = data.data.data;
                        this.page.total = data.data.total;
                    }
                    else{
                        this.tableData = [];
                        this.page.total = 0;
                    }
                    this.tableLoading = false;
                }).catch(err => {
                    this.tableLoading = false;
                    this.$message.error(err.message ? err.message : '数据请求失败，请刷新重试！');
                });
            },
            handleSelectionChange (val) {//当前选中的数据
                this.tableRow = val;
            },
            toggleSelection (row) {//选中第几行
                this.$refs.crud.toggleSelection(row);
            },
            /**
             * @title 数据添加
             * @param row 为当前的数据
             * @param done 为表单关闭函数
             *
             **/
            handleSave (row, done) {
                if(this.tableSearch.classId === ""){
                    this.$message({
                        showClose: true,
                        message: "无效表",
                        type: "warning"
                    });
                    return;
                }
                this.dicID=-1;
                if(row.id) this.$delete(row,'id');
                let flag=false;
                if(row.columnType==='select' || row.columnType==='tree' || row.columnType==='radio' || row.columnType==='checkbox'){
                    row.dictionType=this.dicRadio;
                    flag=true;
                }
                else row.dictionType=0;
                row.classId=this.tableSearch.classId;
                row.subColumn=JSON.stringify(row.subColumn);
                if(row.columnType !== 'select' && row.columnType !== 'tree' && row.columnType !== 'radio'){
                    row.isMultiSelect='false';
                }
                if(row.columnType === 'checkbox'){
                    row.isMultiSelect='true';
                }
                this.saveData('importColumn',row).then(res=>{
                    let data=res.data;
                    const common = ()=>{
                        this.handleList();
                        this.$message({
                            showClose: true,
                            message: "添加成功",
                            type: "success"
                        });
                        done();
                    };
                    if(flag){
                        let dic={};
                        if(row.dictionType === 1){
                            dic={
                                columnId:data.id,
                                dicrionary:JSON.stringify(this.dicData.dicrionary)
                            }
                        }
                        else{
                            dic=this.dicText;
                            dic.columnId=data.id;
                        }
                        this.saveData('importColumnDictionary',dic).then(()=>{
                            common();
                        });
                    }
                    else common();
                });
            },
            handlerefreshChange () {//刷新数据
                this.handleList(this.tableSearch);
                this.$notify({
                    message: `刷新数据成功`,
                    type: 'success',
                });
            },
            /**
             * @title 数据删除
             * @param row 为当前的数据
             * @param index 为当前更新数据的行数
             *
             **/
            handleDel (row) {
                this.$confirm(`是否确认删除字段名为${row.columnName}的配置数据`, "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        this.delData('importColumn',row.id).then(()=>{
                            this.handleList();
                            this.$message({
                                showClose: true,
                                message: "删除成功",
                                type: "success"
                            });
                        });
                    })
                    .catch(err => {
                        console.log(err)
                        this.$message.error(err)
                     });
            },
            /**
             * @title 数据更新
             * @param row 为当前的数据
             * @param index 为当前更新数据的行数
             * @param done 为表单关闭函数
             *
             **/
            handleUpdate (row, index, done) {
                let flag=false;
                if(row.columnType==='select' || row.columnType==='tree' || row.columnType==='radio' || row.columnType==='checkbox'){
                    row.dictionType=this.dicRadio;
                    flag=true;
                }
                else row.dictionType=0;
                row.subColumn=JSON.stringify(row.subColumn);
                if(row.columnType !== 'select' && row.columnType !== 'tree' && row.columnType !== 'radio'){
                    row.isMultiSelect='false';
                }
                if(row.columnType === 'checkbox'){
                    row.isMultiSelect='true';
                }
                this.saveData('importColumn',row).then(()=>{
                    const common = ()=>{
                        this.handleList();
                        this.$message({
                            showClose: true,
                            message: "修改成功",
                            type: "success"
                        });
                        this.dicID=-1;
                        done();
                    };
                    if(flag){
                        let dic={};
                        if(row.dictionType === 1){
                            dic=Object.assign({},this.dicData);
                            dic.columnId=row.id;
                            dic.dicrionary=JSON.stringify(this.dicData.dicrionary);
                        }
                        else{
                            dic=this.dicText;
                            dic.columnId=row.id;
                        }
                        if(this.dicID !== -1){
                            dic.id=this.dicID;
                        }
                        this.saveData('importColumnDictionary',dic).then(()=>{
                            common();
                        });
                    }
                    else common();
                });
            },
            handleSizeChange(val) {//pageSize 改变
                this.page.pageSize=val;
                this.handleList();
            },
            handleCurrentChange(val) {//currentPage 改变
                this.page.currentPage=val
                this.handleList();
            },
            SearchChange () {//搜索按钮
                this.dicDataChange();
                this.handleList();
            },
            handleChange (value) {//字段表单类型 值改变
                let _this=this.$refs.crud;
                _this.tableForm.columnType=value;
                let form=Object.assign({}, _this.tableForm);
                if(value==="select"){
                    this.tableOption.column=getList("all");
                }
                else if(value==="tree"){
                    this.tableOption.column=getList("sectionOne");
                }
                else if(value==="radio" || value==="checkbox"){
                    this.tableOption.column=getList("sectionTwo");
                }
                else{
                    this.tableOption.column=getList();
                }
                // _this.$nextTick(() => {
                //     _this.tableForm=form;
                //     _this.$refs['tableForm'].$nextTick(() => {
                //         _this.$refs['tableForm'].clearValidate();
                //     });
                // });
            },
            rowAdd () { // 新增按钮
                let _this=this.$refs.crud;
                console.log(_this)
                // _this.boxType = 'add';
                // _this.tableForm = Object.assign({}, {});
                this.handleChange('text');
                _this.rowAdd();
            },
            rowEdit (row, index) {// 编辑按钮
                let _this=this.$refs.crud;
                this.handleChange (row.columnType);
                if(row.dictionType==='1' || row.dictionType==='2'){
                    this.dicRadio=parseInt(row.dictionType);
                }
                this.requestMethod('importColumnDictionary/queryDictionaryByColumnId',{columnId:row.id}).then(res=>{
                    let data=res.data;
                    if(!data.data) return;
                    if(row.dictionType==='1'){
                        this.dicData=data.data;
                        this.dicData.dicrionary=JSON.parse(data.data.dicrionary);
                    }
                    else if(row.dictionType==='2'){
                        this.dicData.id=data.data.id;
                        this.dicText=data.data
                    }
                    else {
                        this.dicID=data.data.id;
                    }
                });
                _this.rowEdit(row,index);
            },
            dicAdd () {//字典新增
                if (validatenull(this.dicData.dicrionary)) this.dicData.dicrionary = [];
                this.dicData.dicrionary.push({ label: '', value: '' })
            },
            dicRemove (index) {//字典删除
                this.dicData.dicrionary.splice(index, 1);
            },
            beforeOpen(done,type){//表单显示
                done();
            },
            beforeClose(callack){//表单隐藏
                this.dicData={
                    dicrionary:[]
                };
                this.dicText={};
                this.dicID=-1;
                this.dicRadio=1;
                this.tableOption.column=getList("all");
                callack();
            },
            dicDataChange(){//改变下拉框数据
                this.requestMethod('importColumn/queryColumns',{classId : this.tableSearch.classId}).then(res => {
                    let data=res.data;
                    let subColumn=[];
                    if(data.data && data.data.length > 0){
                        data.data.forEach(item=>{
                            subColumn.push({
                                label: item.columnChn,
                                value: item.columnName,
                            })
                        });
                    }
                    this.tableOption.column.forEach(item=>{
                        if(item.prop === 'subColumn'){
                            item.dicData=subColumn;
                        }
                    })
                });
                let className='';
                this.dicClassName.forEach(item=>{
                    if(item.value===this.tableSearch.classId){
                        className=item.className;
                    }
                });
                this.requestMethod('common/queryField',{module : className}).then(res=>{
                    let data=res.data;
                    let columnName=[];
                    data.data.forEach(item=>{
                        columnName.push({
                            label: item.name,
                            value: item.name,
                        })
                    });
                    this.tableOption.column.forEach(item=>{
                        if(item.prop === 'columnName'){
                            item.dicData=columnName;
                        }
                    })
                })
            }
        }
    }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
    .dialog-dicData {
        width: 100%;
        .item {
            margin-bottom: 10px;
            .item-s {
                display: flex;
                align-items: center;
                & > div {
                    margin-right: 10px;
                }
            }
        }
    }
</style>