<template>
    <div>
        <div class="filters-container">
        #* #foreach($field in $model.fields)
           #if(${field.searchable})
           <el-input placeholder="${field.remark}" size="small" v-model="${field.name}" clearable class="filter-item"></el-input>
           #end
           #end*#
            <el-input v-if="isModulesShow('search')" placeholder="关键字" size="small" v-model="filter1" clearable class="filter-item"></el-input>
            <el-button v-if="isModulesShow('search')" @click="searchData" type="primary" size="small" icon="el-icon-search" class="filter-item">搜索
            </el-button>
            <el-button v-if="isModulesShow('query')" @click="showAdvancedQueryDialog = !showAdvancedQueryDialog" type="primary" size="small"
                       icon="el-icon-search" class="filter-item">高级查询
            </el-button>
            <el-button v-if="isModulesShow('orders')" @click="showTableSortDialog = !showTableSortDialog" type="primary" size="small"
                       icon="el-icon-sort" class="filter-item">排序
            </el-button>
            <el-button v-if="isModulesShow('add')" @click="editRow({id:0,column:${esc.d}route.query.column})" type="primary"
                       size="small" icon="el-icon-edit"
                       class="filter-item">添加
            </el-button>
            <el-button v-if="isModulesShow('excel')" @click="exportExcel" type="primary" size="small" icon="el-icon-share" class="filter-item">导出EXCEL
            </el-button>
            <el-button  @click="goBack" type="primary" size="small"  class="filter-item">返回
            </el-button>
            <el-dropdown trigger="click" size="medium" class="table-column-filter">
                <span>
                  筛选数据<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown" class="table-column-filter-wrapper">
                    <el-checkbox v-for="item in tableColumns" :key="item.value" v-model="item.show">{{item.label}}
                    </el-checkbox>
                </el-dropdown-menu>
            </el-dropdown>
        </div>
        <el-table
                :data="tableData"
                :height="tableHeight"
                row-key="id"
                ref="table"
                size="small"
                border
                v-loading="loading"
        >
            <el-table-column label="${model.remark}" align="center" >
            <el-table-column
                    v-if="multipleMode"
                    align="center"
                    type="selection"
                    width="50">
            </el-table-column>
                <el-table-column
                        label="操作"
                        align="center"
                        fixed="left"
                        min-width="170"
                >
                    <template slot-scope="scope">

                        <el-button v-if="isModulesShow('edit')"  @click="editRow(scope.row)" type="primary" size="mini" plain>编辑</el-button>
                        #if($model.subtables.size()>0)
                            <el-dropdown>
                                <el-button type="primary" size="mini" plain>
                                    更多
                                    <i class="el-icon-arrow-down el-icon--right"></i>
                                </el-button>
                                <el-dropdown-menu slot="dropdown">
                                    #foreach($subtable in $model.subtables)
                                        <el-button @click="${esc.d}router.push({path:'/${subtable.subCode}s',query:{column:scope.row.${subtable.column}+',${subtable.subColumn}'}})" type="primary" size="small" plain>${subtable.name}
                                        </el-button>
                                    #end
                                </el-dropdown-menu>
                            </el-dropdown>
                        #end

                    </template>
                </el-table-column>
            <el-table-column
                    type="index"
                    min-width="50"
                    align="center">
            </el-table-column>
            #foreach($field in $model.fields)
                #if(${field.showInList})

                    #if(${field.formType}=="date"||${field.formType}=="currentDate")
                        <el-table-column
                                v-if="isColumnShow('${field.modelName}')"
                                prop="${field.modelName}"
                                label="$display.alt(${field.remark},${field.modelName})"
                                :formatter="DateFormatter"
                                min-width="100">
                        </el-table-column>
                    #elseif(${field.formType}=="datetime"||${field.formType}=="currentTime")
                        <el-table-column
                                v-if="isColumnShow('${field.modelName}')"
                                prop="${field.modelName}"
                                label="$display.alt(${field.remark},${field.modelName})"
                                :formatter="DateTimeFormatter"
                                min-width="120">
                        </el-table-column>
                    #elseif(${field.formType}=="singleImage")
                        <el-table-column
                                v-if="isColumnShow('${field.modelName}')"
                                prop="${field.modelName}"
                                label="$display.alt(${field.remark},${field.modelName})"
                                min-width="100">
                            <template slot-scope="{row}" v-if="row.${field.modelName}">
                                <img :src="row.${field.modelName}" @click="showImg(row.${field.modelName})" style="width: 100px;height: 100px;vertical-align: middle;" />
                            </template>

                        </el-table-column>
                        #else
                        <el-table-column
                                v-if="isColumnShow('${field.modelName}')"
                                prop="${field.modelName}"
                                label="$display.alt(${field.remark},${field.modelName})"
                                min-width="100">
                        </el-table-column>
                    #end
                #end
            #end

            </el-table-column>
        </el-table>
        <div class="pagination-wrapper">
            <div class="multiple-mode-wrapper">
                <el-button size="small" v-if="!multipleMode" @click="toggleMultipleMode(true)">批量编辑</el-button>
                <el-button-group v-else>
                    <el-button size="small" v-if="isModulesShow('del')"  @click="operation1" type="danger" plain>批量删除</el-button>
                    <el-button size="small" @click="operation2" v-if="0">批量操作2</el-button>
                    <el-button size="small" @click="toggleMultipleMode(false)">取消</el-button>
                </el-button-group>
            </div>
            <el-pagination
                    background
                    @size-change="pageSizeChange"
                    @current-change="currentPageChange"
                    :current-page="currentPage"
                    :page-sizes="[10, 20, 30, 40, 50]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="totalNumber">
            </el-pagination>
        </div>
        <el-dialog title="高级查询" :visible.sync="showAdvancedQueryDialog">
            <el-button @click="addField" type="text" icon="el-icon-plus">添加</el-button>
            <el-table :data="advancedQueryFields">

                <el-table-column prop="link" label="链接符" align="center">
                    <template slot-scope="{row}">
                        <el-select placeholder="链接" size="small" v-model="row.link" class="filter-item" :disabled="row.noChange">
                            <el-option label="AND" value="AND">
                            </el-option>
                            <el-option label="OR" value="OR">
                            </el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="字段" align="center">
                    <template slot-scope="{row}">
                        <el-select v-model="row.name" :disabled="row.noChange">

                            <el-option v-for="item in advancedQueryColumns" :label="item.label" :value="item.value"
                                       :key="item.value"></el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column prop="searchMethod" label="搜索方式" width="150" align="center">
                    <template slot-scope="{row}">
                        <el-select v-model="row.searchMethod" :disabled="row.noChange">
                            <el-option v-for="item in searchMethods" :label="item" :value="item"
                                       :key="item"></el-option>
                        </el-select>
                    </template>
                </el-table-column>


                <el-table-column prop="systemFlag" label="系统参数" width="50" align="center">
                    <template slot-scope="{row}">
                        <el-checkbox v-model="row.systemFlag" :disabled="row.noChange"></el-checkbox>
                    </template>
                </el-table-column>

                <el-table-column prop="value" label="参数" align="center">
                    <template slot-scope="{row}">
                        <el-select v-model="row.value" v-if="row.systemFlag"  :disabled="row.noChange">
                            <el-option v-for="item in systemParameters" :label="item.label" :value="item.value" :key="item.value"></el-option>
                        </el-select>
                        <el-input v-model="row.value" v-else  :disabled="row.noChange"></el-input>

                    </template>
                </el-table-column>

                <el-table-column width="60" align="center">
                    <template slot-scope="{ row, column, ${esc.d}index }">
                        <el-button @click="removeField(${esc.d}index)" size="small" type="text" v-if="!row.noChange">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <span slot="footer" class="dialog-footer">

                <el-button @click="advancedQuery" :loading="${esc.d}store.state.fetchingData">确定</el-button>
            </span>
        </el-dialog>

        <el-dialog title="排序" :visible.sync="showTableSortDialog">
            <el-button @click="addSortField" type="text" icon="el-icon-plus">添加</el-button>
            <el-table :data="tableSortFields">

                <el-table-column prop="name" label="字段" align="center">
                    <template slot-scope="{row}">
                        <el-select v-model="row.name">

                            <el-option v-for="item in advancedQueryColumns" :label="item.label" :value="item.value"
                                       :key="item.value"></el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column prop="order" label="排序" align="center">
                    <template slot-scope="{row}">
                        <el-select v-model="row.order">
                            <el-option label="降序" value="desc">
                            </el-option>
                            <el-option label="升序" value="asc">
                            </el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column width="60" align="center">
                    <template slot-scope="{ row, column, ${esc.d}index }">
                        <el-button @click="removeSortField(${esc.d}index)" size="small" type="text">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <span slot="footer" class="dialog-footer">

                <el-button @click="tableSortQuery" :loading="${esc.d}store.state.fetchingData">确定</el-button>
            </span>
        </el-dialog>

        <el-dialog title="查看图片" :visible.sync="imageDialogVisible" size="small">
            <img width="100%" :src="imgSrc" alt="">
        </el-dialog>

        <el-dialog title="编辑${model.remark}" top='10px' :visible.sync="editDialogVisible">
            <${display.uncapitalize($model.className)} :formData='editRowInfo' @changeEditDialogVisible='changeEditDialogVisible' @changeEdit='changeEdit'></${display.uncapitalize($model.className)}>
        </el-dialog>

    </div>
</template>
<script>
    import {mapState} from 'vuex'
    import {format} from 'date-fns'
    import zh from 'date-fns/locale/zh_cn'
    import ${display.uncapitalize($model.className)} from '../pages/${model.className}'
    export default {
        created() {
            this.getData();
        },
        data() {
            return {
                editRowInfo: {
            #foreach($field in $model.fields)
                #if(${field.formType}=="multiSelect")

                    ${field.modelName} : [],

                #end
                #if(${field.formType}=="currentTime")
                    ${field.modelName} : format(new Date(), 'YYYY/MM/DD HH:mm', { locale: zh }),

                #end
                #if(${field.formType}=="currentDate")
                    ${field.modelName} : format(new Date(), 'YYYY/MM/DD', { locale: zh }),

                #end
                #if(${field.formType}=="loginName")
                    ${field.modelName} : '',

                #end
                #if(${field.formType}=="workNumber")
                    ${field.modelName} : '',

                #end
                #if(${field.formType}=="departId")
                    ${field.modelName} :'',

                #end
            #end
                },
                editDialogVisible: false,
                totalNumber: 0,
                totalPage: 10,
                currentPage: 1,
                pageSize: 20,
                tableData: [],
                filter1: '',
                filter2: '',
                tableColumns: [
                    #foreach($field in $model.fields)
                        #if(${field.showInList})
                            {
                                label: '$display.alt(${field.remark},${field.modelName})',
                                value: '${field.modelName}',
                                show: true
                            },
                        #end
                    #end
                ],
                modules:#if(${model.modules})
                '${model.modules}'.split(',').map(i => String(i))
            #else
            []

#end ,
                multipleMode: false,
                showAdvancedQueryDialog: false,
                advancedQueryFields: [
                #foreach($advancedQueryField in $model.advancedQueryFields)
                    #if(${advancedQueryField.name})
                        {
                            link: '${advancedQueryField.link}',
                            name: '${advancedQueryField.name}',
                            searchMethod: '${advancedQueryField.searchMethod}',
                            value: '${advancedQueryField.value}',
                            #if(${advancedQueryField.noChange})
                                noChange: true,
                            #end
                            #if(${advancedQueryField.systemFlag})
                                systemFlag: true,
                            #end
                        },
                    #end
                #end
            ],
                showTableSortDialog: false,
                tableSortFields: [
                #foreach($sortField in $model.tableSortFields)
                    #if(${sortField.name})
                        {
                            name: '${sortField.name}',
                            order: '${sortField.order}'
                        },
                    #end
                #end
            ],
                searchMethods: ['=', '!=', '>', '>=', '<', '<=', 'like','in'],
                systemParameters: [

                { label: '登录名', value: 'loginName' },
                { label: '工号', value: 'workNumber' },
                { label: '部门', value: 'departId' },
                { label: '当前时间', value: 'currentTime' },
                { label: '当前日期', value: 'currentDate' },
                { label: 'MIS代码', value: 'misCode' },
                { label: 'MIS名称', value: 'misName' },
                { label: '下辖MIS代码', value: 'misChildCode' },
                { label: '下辖MIS名称', value: 'misChildName' },
                { label: '下辖MIS代码和名称', value: 'misChildCodeAndName' },
            ],
                advancedQueryColumns: [
                    #foreach($field in $model.fields)
                        #if(${field.showInList})
                            {
                                label: '$display.alt(${field.remark},${field.modelName})',
                                value: '${field.name}'
                            },
                        #end
                    #end
                ],
                advancedQuerySearchKey: '',
                orderByStr: '',
                imgSrc: '',
                imageDialogVisible: false,
                loading:false,
            }
        },
        computed: {
            ...mapState(['tableHeight','userInfo','childDepartInfo','farmName','farmNO']),
            selection() {
                return this.${esc.d}refs.table.selection.map(i => i.id);
            }
        },
        methods: {
            changeEditDialogVisible(value) {
                this.editDialogVisible = value
            },
            changeEdit() {
                this.editDialogVisible = false
                this.getData();
            },
            pageSizeChange(size) {
                this.currentPage = 1;
                this.pageSize = size;
                this.getData();
            },
            currentPageChange(page) {
                this.currentPage = page;
                this.getData();
            },
            getData() {

                if (this.advancedQueryFields.length > 0) {

                    var templist = [];

                    this.advancedQueryFields.forEach(item => {
                        if (item.link && item.name && item.searchMethod && item.value) {

                        var tempItem = item.link + '_,' + item.name + '_,' + item.searchMethod + '_,';
                        var fieldValue = item.value;
                        if (item.systemFlag) {
                            if (item.value == "currentTime") {
                                fieldValue = format(new Date(), 'YYYY/MM/DD HH:mm', {locale: zh});
                            }
                            if (item.value == "currentDate") {
                                fieldValue = format(new Date(), 'YYYY/MM/DD', {locale: zh});
                            }
                            if (item.value == "departId") {
                                fieldValue = this.userInfo.departId;;
                            }
                            if (item.value == "loginName") {
                                fieldValue = this.userInfo.username;
                            }
                            if (item.value == "workNumber") {
                                fieldValue = this.userInfo.workNumber;
                            }
                            if (item.value == "misCode") {
                                fieldValue = this.farmNO;
                            }
                            if (item.value == "misName") {
                                fieldValue = this.farmName;
                            }
                            if (item.value == "misChildCode") {
                                fieldValue = this.childDepartInfo.misCode;
                            }
                            if (item.value == "misChildName") {
                                fieldValue = this.childDepartInfo.misName;
                            }
                            if (item.value == "misChildCodeAndName") {
                                fieldValue = this.childDepartInfo.misCodeAndName;
                            }
                        }
                        if(fieldValue){
                            tempItem += fieldValue;
                            templist.push(tempItem);
                        }
                    }
                })

                    if (templist.length > 0) {

                        this.advancedQuerySearchKey = templist.join('_;');
                    }
                }


                if (this.tableSortFields.length > 0) {

                    var templist = [];

                    this.tableSortFields.forEach(item => {
                        if (item.name && item.order) {
                        var tempItem = item.name + '_,' + item.order;
                        templist.push(tempItem);
                    }
                })

                    if (templist.length > 0) {

                        this.orderByStr = templist.join('_;');
                    }
                }


                var data = {
                    currentPage: this.currentPage,
                    pageNumber: this.pageSize,
                    searchKey: this.filter1,
                    advancedQuery: this.advancedQuerySearchKey,
                    orderByStr: this.orderByStr,
                }

                if (this.${esc.d}route.query.column) {
                    var tempColumn = this.${esc.d}route.query.column;
                    data[tempColumn.split(',')[1]] = tempColumn.split(',')[0];
                }

                this.loading = true;

                this.${esc.d}http.get({
                    url: '/${display.uncapitalize($model.className)}/page',
                    data: data
                }).then(res => {
                    if (res.success) {
                        this.totalNumber = res.data.page.totalNumber;
                        this.tableData = res.data.pp;
                    }
                    this.loading = false;
                })
            },
            isColumnShow(column) {
                var row = this.tableColumns.find(i => i.value === column);
                return row ? row.show : false;
            },
            isModulesShow(column) {
                var row = this.modules.find(i => i === column);
                return row ? true : false;
            },
            toggleMultipleMode(multipleMode) {
                this.multipleMode = multipleMode;
                if (!multipleMode) {
                    this.${esc.d}refs.table.clearSelection();
                }
            },
            editRow(row) {
                var jsonp = { ...row }

                #foreach($field in $model.fields)
                    #if(${field.formType}=="multiSelect")

                        if(jsonp.${field.modelName}){
                            jsonp.${field.modelName} = jsonp.${field.modelName}.split(',');
                        }else{
                            jsonp.${field.modelName} = [];
                        }

                    #end
                    #if(${field.formType}=="currentTime")
                        jsonp.${field.modelName} = format(new Date(), 'YYYY/MM/DD HH:mm', { locale: zh });

                    #end
                    #if(${field.formType}=="currentDate")
                        jsonp.${field.modelName} = format(new Date(), 'YYYY/MM/DD', { locale: zh });

                    #end
                    #if(${field.formType}=="loginName")
                        jsonp.${field.modelName} = this.userInfo.username;

                    #end
                    #if(${field.formType}=="workNumber")
                        jsonp.${field.modelName} = this.userInfo.workNumber;

                    #end
                    #if(${field.formType}=="departId")
                        jsonp.${field.modelName} = this.userInfo.departId;

                    #end
                #end

                if (this.${esc.d}route.query.column) {
                    jsonp.subColumn = this.${esc.d}route.query.column.split(',')[1];
                    jsonp.subValue = this.${esc.d}route.query.column.split(',')[0];
                }

                if (this.${esc.d}route.query.column) {
                    jsonp[jsonp.subColumn] = jsonp.subValue;
                }

                this.editRowInfo = jsonp
                this.editDialogVisible = true
            },
            operation1() {
                if (this.selection.length > 0) {
                    this.${esc.d}alert('删除将无法恢复，确认要删除么？', '警告', {type: 'error'}).then(() => {
                        return this.${esc.d}http.post({
                            url: '/${display.uncapitalize($model.className)}/del',
                            data: {idStr: this.selection.join()}
                        })
                    }).then(() => {
                        this.${esc.d}message.success('删除成功');
                    this.getData();
                }).catch(action => {
                        if (action === 'cancel') {
                        this.${esc.d}message.info('删除取消');
                    } else {
                        this.${esc.d}message.error('删除失败');
                    }
                })
                }


            },
            operation2() {
                this.${esc.d}notify({
                    title: '提示',
                    message: this.selection
                });

                this.${esc.d}message('操作2');
            },
            addField() {
                this.advancedQueryFields.push({
                    link: 'AND',
                    name: '',
                    searchMethod: '=',
                    value: '',
                });
            },
            removeField(i) {
                if (this.advancedQueryFields.length > 0) {
                    this.advancedQueryFields.splice(i, 1);
                }
            },
            advancedQuery() {

                this.advancedQuerySearchKey = '';

                this.getData();
                this.showAdvancedQueryDialog = false;
            },
            addSortField() {
                this.tableSortFields.push({
                    name: '',
                    order: 'asc',
                });
            },
            removeSortField(i) {
                if (this.tableSortFields.length > 0) {
                    this.tableSortFields.splice(i, 1);
                }
            },
            tableSortQuery() {

                this.orderByStr = '';

                this.getData();
                this.showTableSortDialog = false;
            },
            exportExcel() {
                window.location.href = this.${esc.d}baseUrl + "/${display.uncapitalize($model.className)}/exportExcel?searchKey="
                        + this.filter1 + "&advancedQuery=" + this.advancedQuerySearchKey+"&orderByStr=" + this.orderByStr;
            },
            searchData() {
                this.currentPage = 1;
                this.getData();
            },
            deleteRow(row) {
                this.${esc.d}alert('删除将无法恢复，确认要删除么？', '警告', {type: 'error'}).then(() => {
                    return this.${esc.d}http.post({
                        url: '/${display.uncapitalize($model.className)}/del',
                        data: {id: row.id}
                    })
                }).then(() => {
                    this.${esc.d}message.success('删除成功');
                    this.getData();
                }).catch(action => {
                    if (action === 'cancel') {
                        this.${esc.d}message.info('删除取消');
                    } else {
                        this.${esc.d}message.error('删除失败');
                    }
                })
            },
            DateTimeFormatter(row, column, cellValue) {
                if (cellValue) {
                    return format(cellValue, 'YYYY/MM/DD HH:mm', {locale: zh})
                }

            },
            DateFormatter(row, column, cellValue) {
                if (cellValue) {
                    return format(cellValue, 'YYYY/MM/DD', {locale: zh})
                }

            },
            showImg(img) {
                this.imgSrc = img;
                this.imageDialogVisible = true;
            },
            goBack() {
                this.$router.go(-1);
            },

        },
    components: {
        ${display.uncapitalize($model.className)}
    }
    }
</script>
<style lang="less" scoped>

</style>
