<template>
    <div class="list-view">
        <div class="filters-container">
            <div>
                <el-col :span="7">
                    <span class="span-size">申请年度</span>
                    <el-select
                        v-model="year"
                        placeholder="请选择年度"
                        class="filter-item"
                        clearable
                        style="width: 220px"
                        @change="getData"
                    >
                        <el-option v-for="item in years" :key="item" :value="item" :label="item + '年'"></el-option>
                    </el-select>
                </el-col>
                <el-col :span="7">
                    <span class="span-size">承办单位名称</span>
                    <el-input
                        placeholder="输入承办单位名称"
                        v-model="search"
                        clearable
                        class="filter-item"
                        style="width: 220px"
                        @change="getData"
                    ></el-input>
                </el-col>
                <el-col :span="10">
                    <label class="span-size">申请时间</label>
                    <el-date-picker
                        v-model="dateRange"
                        type="daterange"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        start-placeholder="请选择开始时间"
                        end-placeholder="请选择结束时间"
                        range-separator="至"
                        :default-time="['00:00:00', '23:59:59']"
                        class="filter-item"
                        @change="getData"
                    >
                    </el-date-picker>
                </el-col>
            </div>
            <div>
                <el-col :span="7">
                    <label class="span-size">申请状态</label>
                    <el-select
                        class="filter-item"
                        v-model="status"
                        clearable
                        placeholder="请选择状态"
                        style="width: 220px"
                        @change="getData"
                    >
                        <el-option
                            v-for="item in statusOptions"
                            :key="item.value"
                            :value="item.value"
                            :label="item.label"
                        ></el-option>
                    </el-select>
                </el-col>
                <el-col :span="7">
                    <label class="span-size">申请评定等级</label>
                    <el-select
                        style="width: 220px"
                        v-model="grade"
                        placeholder="请选择的等级"
                        class="filter-item"
                        multiple
                        clearable
                        @change="getData"
                    >
                        <el-option
                            v-for="item in gradeOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        ></el-option>
                    </el-select>
                </el-col>
            </div>
            <div style="padding-left: 10px">
                <el-col :span="24">
                    <el-button
                        @click="download"
                        type="primary"
                        icon="el-icon-download"
                        :loading="downloading"
                        class="filter-item"
                        :disabled="totalElements <= 0"
                        >导出EXCEL
                    </el-button>
                </el-col>
            </div>
        </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 v-if="multipleMode" align="center" type="selection" width="50"> </el-table-column>
            <!-- <el-table-column prop="id" label="ID" width="100"> </el-table-column> -->
            <el-table-column prop="name" label="承办单位"> </el-table-column>
            <el-table-column prop="createdAt" label="申请时间" min-width="100"></el-table-column>
            <el-table-column prop="year" label="年度" min-width="60"> </el-table-column>
            <el-table-column prop="gradingOrganization" label="考级机构" min-width="100"> </el-table-column>
            <el-table-column prop="status1" label="状态" min-width="100"> </el-table-column>
            <el-table-column prop="score" label="分数">
                <template slot-scope="{ row }">
                    <span v-if="row.score">{{ row.score }}</span>
                    <span v-else>暂无</span>
                </template>
            </el-table-column>
            <el-table-column prop="grade" label="等级">
                <template slot-scope="{ row }">
                    <span v-if="row.grade == '优秀'"><el-link :underline="false" type="success">优秀</el-link></span>
                    <span v-else-if="row.grade == '合格'"
                        ><el-link :underline="false" type="warning">合格</el-link></span
                    >
                    <span v-else-if="row.grade == '不合格'"
                        ><el-link :underline="false" type="danger">不合格</el-link></span
                    >
                    <span v-else><el-link type="info" :underline="false">暂无</el-link></span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="right" fixed="right" :width="moreWidth + 'px'">
                <template slot-scope="{ row }">
                    <el-button
                        size="mini"
                        @click="accept(row)"
                        type="success"
                        plain
                        v-if="row.status == 'FIRST_REVIEW_PENDING'"
                        >受理</el-button
                    >
                    <el-button
                        @click="editRow(row)"
                        type="primary"
                        size="mini"
                        plain
                        v-if="row.status !== 'FIRST_REVIEW_PENDING'"
                    >
                        <span v-if="row.status == 'FIRST_REVIEW_PENDING' || row.status == 'ACCEPT'">审核材料</span>
                        <span v-else>查看材料</span>
                    </el-button>
                    <el-button
                        v-if="
                            row.status === 'ACCEPT' ||
                                row.status === 'FIRST_REVIEW_COMPLETED' ||
                                row.status === 'REVIEW_DENY'
                        "
                        :loading="row.loading"
                        @click="audit(row, 'ASSIGN_EXPERT', '区文旅局已审核上报')"
                        type="success"
                        size="mini"
                        plain
                    >
                        同意上报
                    </el-button>
                    <el-button
                        v-if="
                            row.status === 'ACCEPT' ||
                                row.status === 'FIRST_REVIEW_COMPLETED' ||
                                row.status === 'REVIEW_DENY'
                        "
                        :loading="row.loading"
                        @click="dismiss(row)"
                        type="warning"
                        size="mini"
                        plain
                    >
                        退回申请
                    </el-button>
                    <el-button
                        v-if="row.status === 'SUBMIT_PAPER_MATERIALS'"
                        type="success"
                        plain
                        size="mini"
                        @click="saveComplete(row)"
                        :loading="row.loading"
                        >收取纸质材料</el-button
                    >
                    <!-- <el-button @click="deleteRow(row)" type="danger" size="mini" plain>删除</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 title="退回缘由" :visible.sync="dialogDismiss" width="500px" center>
            <div style="height: 150px;width:330px;margin:2px auto">
                <label style="margin-right: 10px">退回缘由</label>
                <el-select
                    v-model="reason"
                    filterable
                    allow-create
                    default-first-option
                    clearable
                    placeholder="请选择缘由"
                    style="width: 70%"
                >
                    <el-option v-for="item in dismissReason" :key="item" :label="item" :value="item"> </el-option>
                </el-select>
                <div style="margin: 45px 0 0 240px">
                    <el-button type="primary" @click="saveDismiss">确认</el-button>
                </div>
            </div>
        </el-dialog> -->
        <el-dialog title="退回缘由" :visible.sync="dialogDismiss" width="500px" center>
            <div style="height: 150px;width:400px;margin:2px auto">
                <el-input
                    type="textarea"
                    v-model="reason"
                    :autosize="{ minRows: 4, maxRows: 4 }"
                    placeholder="请输入退回缘由"
                ></el-input>
                <div style="margin: 20px 0 0 345px">
                    <el-button type="primary" @click="saveDismiss">确认</el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { mapState } from 'vuex';
import pageableTable from '@/mixins/pageableTable';
import rateStatus from '@/mixins/rateStatus';

export default {
    name: 'RateDistrictListPending',
    mixins: [pageableTable, rateStatus],
    data() {
        return {
            multipleMode: false,
            search: '',
            url: '/rate/all2',
            downloading: false,
            supervisor: [],
            dialogVisible: false,
            rateId: '',
            gradeOptions: [
                { label: '优秀', value: 'EXCELLENT' },
                { label: '合格', value: 'ELIGIBLE' },
                { label: '不合格', value: 'NOT_ELIGIBLE' }
            ],
            dialogDismiss: false,
            reason: '',
            dismissReason: ['资料不全', '缺少附件', '无资格'],
            form: {},
            grade: '',
            status: [],
            loading: false,
            years: [2021, 2022, 2023, 2024, 2025],
            year: '',
            dateRange: ''
        };
    },
    computed: {
        selection() {
            return this.$refs.table.selection.map(i => i.id);
        },
        ...mapState(['userInfo']),
        moreWidth() {
            let larges = ['FIRST_REVIEW_COMPLETED', 'FIRST_REVIEW_COMPLETED', 'ACCEPT', 'REVIEW_DENY'];
            let mendus = ['SUBMIT_PAPER_MATERIALS'];

            let list = [...this.tableData];
            let size = 100;
            for (var i = 0; i < list.length; i++) {
                if (larges.includes(list[i].status)) {
                    size = 300;
                    break;
                }
                if (mendus.includes(list[i].status)) {
                    size = 200;
                    continue;
                }
            }

            return size;
        }
    },
    mounted() {
        this.$http
            .post('/user/authority', { authorityName: 'ROLE_EXPERT' })
            .then(res => {
                this.supervisor = res;
            })
            .catch(e => {
                console.log(e);
                this.$message.error(e.error);
            });
    },
    methods: {
        gradeFormatter(row, column, cellValue, index) {
            let selectedOption = this.gradeOptions.find(i => i.value === cellValue);
            if (selectedOption) {
                return selectedOption.label;
            }
            return '';
        },
        beforeGetData() {
            let data = {
                sort: 'createdAt,desc',
                query: {
                    submit: true,
                    district: this.userInfo.district,
                    status: ['FIRST_REVIEW_PENDING', 'ACCEPT', 'FIRST_REVIEW_COMPLETED', 'REVIEW_DENY']
                }
            };
            if (this.search) {
                data.search = this.search;
            }
            if (this.status.length > 0) {
                data.query.status = this.status;
            }
            if (this.grade) {
                data.query.grade = this.grade;
            }
            if (this.dateRange && this.dateRange.length > 0) {
                data.query.createdAt = this.dateRange[0] + ',' + this.dateRange[1];
            }
            if (this.year) {
                data.query.year = this.year;
            }
            return data;
        },
        toggleMultipleMode(multipleMode) {
            this.multipleMode = multipleMode;
            if (!multipleMode) {
                this.$refs.table.clearSelection();
            }
        },
        addRow() {
            this.$router.push({
                path: '/rateEdit',
                query: {
                    ...this.$route.query
                }
            });
        },
        editRow(row) {
            this.$router.push({
                path: '/organization',
                query: {
                    id: row.id,
                    status: row.status
                }
            });
        },
        download() {
            this.downloading = true;
            let params = { size: 1000, query: { submit: true } };
            if (this.grade.length > 0) {
                params.query.grade = this.grade;
            }

            if (this.status) {
                params.query.status = this.status;
            } else {
                params.query.status = ['FIRST_REVIEW_PENDING', 'ACCEPT', 'FIRST_REVIEW_COMPLETED'];
            }

            this.$axios
                .post('/rate/excel', params, {
                    responseType: 'blob'
                })
                .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(`/rate/del/${row.id}`);
                })
                .then(() => {
                    this.$message.success('删除成功');
                    this.getData();
                })
                .catch(e => {
                    if (e !== 'cancel') {
                        this.$message.error(e.error);
                    }
                });
        },
        audit(row, status, remark) {
            this.$set(row, 'loading', true);
            if (row.status === 'ACCEPT' || row.status === 'REVIEW_DENY') {
                this.$alert('请先审核材料，并确认已审核完成', '提示', {
                    confirmButtonText: '确认',
                    callback: action => {
                        this.editRow(row);
                    }
                });
            } else {
                this.$confirm('确认此承办单位同意上报?', '提示', {
                    confirmButtonText: '同意上报',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        this.$http
                            .post('/rate/audit', {
                                id: row.id,
                                status: status,
                                score: 0,
                                remark: remark
                            })
                            .then(res => {
                                this.$set(row, 'loading', false);
                                this.$message.success('上报成功');
                                this.getData();
                            })
                            .catch(e => {
                                console.log(e);
                                this.$set(row, 'loading', false);
                                this.$message.error(e.error);
                            });
                    })
                    .catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消'
                        });
                        this.$set(row, 'loading', false);
                    });
            }
        },
        dismiss(row) {
            if (row.status === 'ACCEPT' || row.status === 'REVIEW_DENY') {
                this.$alert('请先审核材料，并确认已审核完成', '提示', {
                    confirmButtonText: '确认',
                    callback: action => {
                        this.editRow(row);
                    }
                });
            } else {
                this.dialogDismiss = true;
                this.form = row;
            }
        },
        saveDismiss() {
            let row = this.form;
            this.$set(row, 'loading', true);
            this.$http
                .post('/rate/audit', {
                    id: this.form.id,
                    status: 'FIRST_REVIEW_DENY',
                    score: 0,
                    remark: this.reason
                })
                .then(res => {
                    this.$set(row, 'loading', false);
                    this.$message.success('退回成功');
                    this.getData();
                })
                .catch(e => {
                    this.$set(row, 'loading', false);
                    console.log(e);
                    this.$message.error(e.error);
                });
            this.form = '';
            this.reason = '';
            this.dialogDismiss = false;
        },
        supervision(id) {
            this.$router.push({
                path: '/assignExpert',
                query: {
                    id: id
                }
            });
            // this.dialogVisible = true;
            // this.rateId = id;
        },
        addRegulatory(id) {
            this.$http
                .post('/rate/addExpert', {
                    id: this.rateId,
                    userId: id
                })
                .then(res => {
                    this.saving = false;
                    this.$message.success('成功');
                    this.dialogVisible = false;
                    this.recordId = '';
                    this.getData();
                })
                .catch(e => {
                    console.log(e);
                    this.saving = false;
                    this.$message.error(e.error);
                });
        },
        saveComplete(row) {
            this.$set(row, 'loading', true);
            this.$confirm('确认已收到承办单位提交的纸质材料?', '提示', {
                confirmButtonText: '已收到',
                cancelButtonText: '暂未收到',
                type: 'warning'
            })
                .then(() => {
                    this.$http
                        .post('/rate/paperMaterial', {
                            id: row.id,
                            status: 'COLLECT_PAPER_MATERIALS',
                            remark: '区文旅局已确认收到承办单位提交的纸质材料'
                        })
                        .then(res => {
                            this.$message.success('确认成功');
                            this.getData();
                        })
                        .catch(e => {
                            console.log(e);
                            this.$message.error(e.error);
                        });
                })
                .catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    });
                    this.$set(row, 'loading', false);
                });
        },
        accept(row) {
            this.$confirm('确认受理吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    let data = { ...row };
                    console.log(data);
                    data.status = 'ACCEPT';
                    this.$http
                        .post('/rate/save', data, { body: 'json' })
                        .then(res => {
                            this.$nextTick(() => {
                                let audit = {
                                    rateId: res.id,
                                    remark: '区文旅局已受理，等待审核',
                                    status: 'ACCEPT'
                                };
                                this.$http.post('/rateAudit/save', audit, {
                                    body: 'json'
                                });
                            });
                            this.$message.success('受理成功');
                            this.getData();
                        })
                        .catch(e => {
                            console.log(e);
                            this.$message.error(e.error);
                        });
                })
                .catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消受理'
                    });
                });
        }
    }
};
</script>
<style lang="less" scoped>
.el-link {
    font-size: 12px;
}
.span-size {
    font-size: 14px;
    color: #565b66;
    line-height: 15px;
    padding: 0 10px 0 10px;
}
</style>
