<template>
    <div class="list-view">
        <div class="filters-container">
            <el-input placeholder="审批名称/发起人" v-model="search" clearable class="filter-item"></el-input>
            <el-select v-model="status" class="filter-item">
                <el-option label="待办" :value="0"></el-option>
                <el-option label="已办" :value="1"></el-option>
                <el-option label="完成" :value="2"></el-option>
            </el-select>
            <el-button @click="getData" type="primary" icon="el-icon-search" class="filter-item">搜索 </el-button>
            <el-button @click="addRow" type="primary" icon="el-icon-plus" class="filter-item">发起审批 </el-button>
            <!-- <el-button
                @click="download"
                type="primary"
                icon="el-icon-download"
                :loading="downloading"
                class="filter-item"
                >导出EXCEL
            </el-button> -->
        </div>
        <el-table
            :data="tableData"
            row-key="id"
            ref="table"
            header-row-class-name="table-header-row"
            header-cell-class-name="table-header-cell"
            row-class-name="table-row"
            cell-class-name="table-cell"
            :height="tableHeight"
        >
            <el-table-column prop="id" label="ID" width="100"> </el-table-column>
            <el-table-column prop="approval.name" label="审批名称"> </el-table-column>
            <el-table-column prop="approval.creator" label="发起人"> </el-table-column>
            <el-table-column prop="approval.createdAt" label="发起时间" width="150"> </el-table-column>
            <el-table-column prop="status" label="状态" :formatter="statusFormatter"> </el-table-column>
            <el-table-column
                prop="approval.status"
                label="当前流程"
                :formatter="approvalStatusFormatter"
            ></el-table-column>
            <el-table-column prop="approval.currentApprover" label="当前审批人"> </el-table-column>
            <el-table-column label="附件" width="70" align="center" fixed="right">
                <template v-slot="{ row }">
                    <el-button type="text" @click="viewAttach(row)">查看</el-button>
                </template>
            </el-table-column>
            <el-table-column label="流转记录" align="center" fixed="right" width="70">
                <template v-slot="{ row }">
                    <el-button type="text" @click="viewHistory(row)">查看</el-button>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" fixed="right" width="150">
                <template slot-scope="{ row }" v-if="row.status === 'PENDING'">
                    <el-button v-if="row.level === 0" size="mini">提交审批</el-button>
                    <el-button v-if="row.level > 0" size="mini" @click="next(row)">审批</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination-wrapper">
            <!-- <div class="multiple-mode-wrapper">
                <el-button v-if="!multipleMode" @click="toggleMultipleMode(true)">批量编辑</el-button>
                <el-button-group v-else>
                    <el-button @click="operation1">批量操作1</el-button>
                    <el-button @click="operation2">批量操作2</el-button>
                    <el-button @click="toggleMultipleMode(false)">取消</el-button>
                </el-button-group>
            </div> -->
            <el-pagination
                background
                @size-change="onSizeChange"
                @current-change="onCurrentChange"
                :current-page="page"
                :page-sizes="[10, 20, 30, 40, 50]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalElements"
            >
            </el-pagination>
        </div>
        <el-dialog :visible="showAddDialog" title="发起审批">
            <div>
                <el-form :model="formData" label-position="right" label-width="120px" :rules="rules" ref="form">
                    <el-form-item label="审批名称" prop="name">
                        <el-input v-model="formData.name"></el-input>
                    </el-form-item>
                    <el-form-item label="附件" prop="attach">
                        <file-upload v-model="formData.attach" format="json"></file-upload>
                    </el-form-item>
                    <el-form-item label="报送" prop="approver1">
                        <el-select v-model="formData.approver1" multiple>
                            <el-option
                                v-for="item in approvers[0]"
                                :key="item.id"
                                :label="item.name"
                                :value="item.userId"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>
            <div slot="footer">
                <el-button size="mini" @click="showAddDialog = false" :disabled="saving">取消</el-button>
                <el-button size="mini" @click="save" :loading="saving" type="primary">保存</el-button>
            </div>
        </el-dialog>

        <el-dialog title="审批" :visible.sync="showNextDialog">
            <el-form
                :model="approvalForm"
                :rules="approvalFormRules"
                label-position="right"
                label-width="80px"
                ref="approvalForm"
            >
                <el-form-item label="审批意见" prop="pass">
                    <el-radio v-model="approvalForm.pass" :label="true">通过</el-radio>
                    <el-radio v-model="approvalForm.pass" :label="false">不通过</el-radio>
                </el-form-item>
                <el-form-item label="审批备注" prop="remark">
                    <el-input v-model="approvalForm.remark" type="textarea"></el-input>
                </el-form-item>
                <el-form-item label="报送" prop="nextApprovers">
                    <el-select v-model="approvalForm.nextApprovers" multiple>
                        <el-option
                            v-for="item in nextApproversOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.userId"
                        ></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="showNextDialog = false" :disabled="nextSaving" size="mini">取消</el-button>
                <el-button @click="finishNext" type="primary" size="mini" :loading="nextSaving">结束流转</el-button>
                <el-button @click="saveNext" type="primary" size="mini" :loading="nextSaving">提交</el-button>
            </div>
        </el-dialog>
        <el-dialog :visible.sync="showHistoryDialog" title="流转记录" width="800px">
            <el-steps direction="vertical" :active="history.length" space="100" v-loading="loadingHistory">
                <el-step :title="getTitle(item)" v-for="item in history" :key="item.id" status="finish">
                    <div slot="description" class="history-item">
                        <div>
                            <div class="label">审批人：</div>
                            <div class="value">{{ item.approver }}</div>

                            <div class="label">审批结果：</div>
                            <div class="value">{{ item.status === 'PASS' ? '通过' : '不通过' }}</div>

                            <div class="label">审批时间：</div>
                            <div class="value" style="width:140px">{{ item.approvalTime }}</div>
                        </div>
                        <div v-if="item.remark">审批备注：{{ item.remark }}</div>
                    </div>
                </el-step>
            </el-steps>
        </el-dialog>

        <el-dialog title="附件" :visible.sync="showAttachDialog">
            <el-table :data="attaches">
                <el-table-column label="文件" prop="name"> </el-table-column>
                <el-table-column label="操作" align="center" width="80">
                    <template v-slot="{ row }">
                        <el-button size="mini" @click="openFile(row)">下载</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div slot="footer">
                <el-button size="mini" @click="showAttachDialog = false">关闭</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { mapState } from 'vuex';
import pageableTable from '@/mixins/pageableTable';

export default {
    name: 'ApprovalList',
    mixins: [pageableTable],
    data() {
        return {
            sortStr: 'createdAt,desc',
            multipleMode: false,
            search: '',
            url: '/approvalProcess/my',
            downloading: false,
            statusOptions: [
                { label: '拟稿', value: 'DRAFT' },
                { label: '一级审批', value: 'LEVEL_1' },
                { label: '二级审批', value: 'LEVEL_2' },
                { label: '三级审批', value: 'LEVEL_3' },
                { label: '四级审批', value: 'LEVEL_4' },
                { label: '五级审批', value: 'LEVEL_5' },
                { label: '完成', value: 'FINISH' }
            ],
            showAddDialog: false,
            formData: {},
            saving: false,
            rules: {
                name: [{ required: true, message: '请输入名称' }],
                attach: [
                    {
                        validator: (rule, value, callback) => {
                            if (value instanceof Array && value.length) {
                                callback();
                            } else {
                                callback(new Error('请上传附件'));
                            }
                        }
                    }
                ],
                approver1: [
                    {
                        validator: (rule, value, callback) => {
                            if (value instanceof Array && value.length) {
                                callback();
                            } else {
                                callback(new Error('请选择一级审批人'));
                            }
                        }
                    }
                ],
                approver2: [
                    {
                        validator: (rule, value, callback) => {
                            if (value instanceof Array && value.length) {
                                callback();
                            } else {
                                callback(new Error('请选择二级审批人'));
                            }
                        }
                    }
                ],
                approver3: [
                    {
                        validator: (rule, value, callback) => {
                            if (value instanceof Array && value.length) {
                                callback();
                            } else {
                                callback(new Error('请选择三级审批人'));
                            }
                        }
                    }
                ],
                approver4: [
                    {
                        validator: (rule, value, callback) => {
                            if (value instanceof Array && value.length) {
                                callback();
                            } else {
                                callback(new Error('请选择四级审批人'));
                            }
                        }
                    }
                ],
                approver5: [
                    {
                        validator: (rule, value, callback) => {
                            if (value instanceof Array && value.length) {
                                callback();
                            } else {
                                callback(new Error('请选择五级审批人'));
                            }
                        }
                    }
                ]
            },
            approvers: [[], [], [], [], []],
            nextApproversOptions: [],
            approvalForm: {
                pass: null,
                remark: null,
                nextApprovers: []
            },
            showNextDialog: false,
            approvalFormRules: {
                pass: [{ required: true, message: '请选择审批意见' }],
                nextApprovers: [
                    {
                        validator: (rule, value, callback) => {
                            if (value instanceof Array && value.length) {
                                callback();
                            } else {
                                callback(new Error('请选择报送人员'));
                            }
                        }
                    }
                ]
            },
            nextSaving: false,
            history: [],
            showHistoryDialog: false,
            loadingHistory: false,
            status: 0,
            attaches: [],
            showAttachDialog: false
        };
    },
    created() {
        this.$http.get('/approver/all', { size: 10000 }).then(res => {
            let approvers = [[], [], [], [], []];
            res.content.forEach(i => {
                approvers[i.level - 1].push(i);
            });
            this.approvers = approvers;
        });
    },
    computed: {
        selection() {
            return this.$refs.table.selection.map(i => i.id);
        }
    },
    methods: {
        statusFormatter(row, column, cellValue, index) {
            if (row.status === 'PENDING') return '待办';
            else if (row.approval.status === 'FINISH') return '完结';
            return '已办';
        },
        approvalStatusFormatter(row, column, cellValue, index) {
            return (this.statusOptions.find(i => i.value === cellValue) || {}).label;
        },
        beforeGetData() {
            return { search: this.search, status: this.status };
        },
        toggleMultipleMode(multipleMode) {
            this.multipleMode = multipleMode;
            if (!multipleMode) {
                this.$refs.table.clearSelection();
            }
        },
        addRow() {
            this.formData = {};
            this.showAddDialog = true;
        },
        editRow(row) {},
        download() {
            this.downloading = true;
            this.$axios
                .get('/approval/excel', {
                    responseType: 'blob',
                    params: { size: 10000 }
                })
                .then(res => {
                    console.log(res);
                    this.downloading = false;
                    const downloadUrl = window.URL.createObjectURL(new Blob([res.data]));
                    const link = document.createElement('a');
                    link.href = downloadUrl;
                    link.setAttribute('download', res.headers['content-disposition'].split('filename=')[1]);
                    document.body.appendChild(link);
                    link.click();
                    link.remove();
                })
                .catch(e => {
                    console.log(e);
                    this.downloading = false;
                    this.$message.error(e.error);
                });
        },
        operation1() {
            this.$notify({
                title: '提示',
                message: this.selection
            });
        },
        operation2() {
            this.$message('操作2');
        },
        deleteRow(row) {
            this.$alert('删除将无法恢复，确认要删除么？', '警告', { type: 'error' })
                .then(() => {
                    return this.$http.post(`/approval/del/${row.id}`);
                })
                .then(() => {
                    this.$message.success('删除成功');
                    this.getData();
                })
                .catch(e => {
                    if (e !== 'cancel') {
                        this.$message.error(e.error);
                    }
                });
        },
        save() {
            this.$refs.form.validate().then(valid => {
                this.saving = true;
                this.$http
                    .post('/approval/create', this.formData, { body: 'json' })
                    .then(res => {
                        return this.$http.get('/approvalProcess/startProcess', { id: res.id });
                    })
                    .then(res => {
                        this.saving = false;
                        this.showAddDialog = false;
                        this.$message.success('保存成功');
                        this.getData();
                    })
                    .catch(e => {
                        this.saving = false;
                        this.$message.error(e.error || '保存失败');
                    });
            });
        },
        startProcess(row) {
            this.$confirm('确认提交审批?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {})
                .catch(() => {});
        },
        next(row) {
            this.approvalForm = {
                id: row.id,
                pass: null,
                remark: null,
                nextApprovers: []
            };
            this.nextApproversOptions = [];
            if (row.level < 5) {
                this.$http.get('/approver/all', { size: 10000, query: { level: row.level + 1 } }).then(res => {
                    this.nextApproversOptions = res.content;
                });
            }

            this.showNextDialog = true;
        },
        saveNext() {
            this.approvalFormRules = {
                pass: [{ required: true, message: '请选择审批意见' }],
                nextApprovers: [
                    {
                        validator: (rule, value, callback) => {
                            if (value instanceof Array && value.length) {
                                callback();
                            } else {
                                callback(new Error('请选择报送人员'));
                            }
                        }
                    }
                ]
            };
            this.$nextTick(() => {
                if (this.$refs.approvalForm) {
                    this.$refs.approvalForm.clearValidate();
                }
                this.$refs.approvalForm.validate().then(() => {
                    this.nextSaving = true;
                    this.$http
                        .post('/approvalProcess/next', {
                            ...this.approvalForm,
                            nextApprovers: this.approvalForm.nextApprovers.join()
                        })
                        .then(res => {
                            this.$message.success('提交成功');
                            this.nextSaving = false;
                            this.showNextDialog = false;
                            this.getData();
                        })
                        .catch(e => {
                            this.nextSaving = false;
                            this.$message.error(e.error || '提交失败');
                        });
                });
            });
        },
        finishNext() {
            this.approvalFormRules = {
                pass: [{ required: true, message: '请选择审批意见' }]
            };
            this.$nextTick(() => {
                if (this.$refs.approvalForm) {
                    this.$refs.approvalForm.clearValidate();
                }
                this.$refs.approvalForm.validate().then(() => {
                    this.nextSaving = true;
                    this.$http
                        .post('/approvalProcess/next', {
                            ...this.approvalForm
                        })
                        .then(res => {
                            this.$message.success('提交成功');
                            this.nextSaving = false;
                            this.showNextDialog = false;
                            this.getData();
                        })
                        .catch(e => {
                            this.nextSaving = false;
                            this.$message.error(e.error || '提交失败');
                        });
                });
            });
        },
        viewHistory(row) {
            this.loadingHistory = true;
            this.history = [];
            this.$http
                .get('/approvalProcess/all', {
                    size: 1000,
                    sort: 'approvalTime',
                    query: {
                        approvalId: row.approvalId,
                        status: 'PASS,DENY'
                    }
                })
                .then(res => {
                    this.history = res.content;
                    this.loadingHistory = false;
                });
            this.showHistoryDialog = true;
        },
        viewAttach(row) {
            this.attaches = row.approval.attach;
            this.showAttachDialog = true;
        },
        getTitle(row) {
            switch (row.level) {
                case 0:
                    return '拟稿';
                case 1:
                    return '一级审批';
                case 2:
                    return '二级审批';
                case 3:
                    return '三级审批';
                case 4:
                    return '四级审批';
                case 5:
                    return '五级审批';
            }
        },
        openFile(row) {
            window.open(row.url, '_blank');
            // let el = document.createElement('a');
            // el.download = row.name;
            // el.href = row.url;
            // el.click();
        }
    }
};
</script>
<style lang="less" scoped>
.history-item {
    margin-bottom: 30px;
    .label {
        display: inline-block;
    }
    .value {
        display: inline-block;
        width: 140px;
    }
}
</style>
