<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"
                        @keyup.enter.native="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>
                <!-- <el-col :span="8">
                    <span class="span-size">考级机构</span>
                    <el-select
                        v-model="agency"
                        placeholder="所属考级机构"
                        multiple
                        class="filter-item"
                        style="width: 220px"
                        @change="getData"
                    >
                        <el-option
                            v-for="(item, index) in examination"
                            :key="index"
                            :value="item.value"
                            :label="item.label"
                        ></el-option>
                    </el-select>
                </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 statusOptions2"
                            :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 v-model="district" style="width: 220px" @change="getData" clearable>
                        <el-option
                            v-for="item in districts"
                            :key="item.id"
                            :value="item.name"
                            :label="item.name"
                        ></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-button @click="getData" type="primary" icon="el-icon-search" class="filter-item">查询 </el-button> -->
                <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="district" label="地址" min-width="100">
                <template slot-scope="{ row }"> 江苏省{{ row.district }} </template>
            </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 :underline="false" type="info">暂无</el-link></span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="right" fixed="right" :width="moreWidth ? '300px' : '100px'">
                <template slot-scope="{ row }">
                    <el-button @click="editRow(row)" type="primary" size="mini" plain>
                        <span v-if="row.status == 'ASSIGN_EXPERT'">审核材料</span>
                        <span v-else-if="row.status == 'SUBMIT_GRADE'">最终评审</span>
                        <span v-else>查看材料</span>
                    </el-button>
                    <el-button
                        @click="supervision(row.id)"
                        type="success"
                        size="mini"
                        plain
                        v-if="row.status === 'ASSIGN_EXPERT'"
                        >分配专家组</el-button
                    >
                    <el-button
                        v-if="row.status === 'ASSIGN_EXPERT'"
                        :loading="row.loading"
                        @click="dismiss(row)"
                        type="warning"
                        size="mini"
                        plain
                    >
                        退回申请
                    </el-button>
                    <el-button
                        v-if="row.status === 'COLLECT_PAPER_MATERIALS'"
                        type="success"
                        plain
                        size="mini"
                        @click="saveComplete(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 title="分配市政专家" :visible.sync="dialogVisible" width="500px" center>
            <div>
                <el-table :data="supervisor">
                    <el-table-column prop="nickname" label="昵称"></el-table-column>
                    <el-table-column prop="phone" label="手机号"></el-table-column>
                    <el-table-column label="操作" align="center" fixed="right" min-width="80">
                        <template slot-scope="{ row }">
                            <el-button @click="addRegulatory(row.id)" type="success" size="mini" plain>确认</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </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: 'RateListPending',
    mixins: [pageableTable, rateStatus],
    data() {
        return {
            multipleMode: false,
            search: '',
            url: '/rate/all2',
            downloading: false,
            supervisor: [],
            dialogVisible: false,
            rateId: '',
            dialogScore: false,
            gradeOptions: [
                { label: '优秀', value: 'EXCELLENT' },
                { label: '合格', value: 'ELIGIBLE' },
                { label: '不合格', value: 'NOT_ELIGIBLE' }
            ],
            dialogDismiss: false,
            reason: '',
            dismissReason: ['资料不全', '缺少附件', '无资格'],
            form: {},
            grade: '',
            status: [],
            years: [2021, 2022, 2023, 2024, 2025],
            year: '',
            districts: [],
            district: '',
            dateRange: ''
        };
    },
    created() {
        // this.$http
        //     .post('/gradingOrganization/all', { size: 1000 }, { body: 'json' })
        //     .then(res => {
        //         if (res.content.length > 0) {
        //             res.content.forEach(item => {
        //                 this.examination.push({
        //                     label: item.name,
        //                     value: item.id
        //                 });
        //             });
        //         }
        //     })
        //     .catch(e => {
        //         console.log(e);
        //     });
        this.$http
            .post('/setting/byFlag', { flag: 2 })
            .then(res => {
                this.districts = res;
            })
            .catch(e => {
                console.log(e);
                this.$message.error(e.error);
            });
    },
    computed: {
        selection() {
            return this.$refs.table.selection.map(i => i.id);
        },
        ...mapState(['userInfo']),
        moreWidth() {
            let info = [...this.tableData].find(item => {
                return item.status === 'ASSIGN_EXPERT';
            });

            return !!info;
        }
    },
    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: 'sort,desc;createdAt,desc',
                query: {
                    submit: true,
                    status: ['ASSIGN_EXPERT', 'SUBMIT_GRADE', 'COLLECT_PAPER_MATERIALS']
                }
            };

            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.year) {
                data.query.year = this.year;
            }
            if (this.district) {
                data.query.district = this.district;
            }
            if (this.dateRange && this.dateRange.length > 0) {
                data.query.createdAt = this.dateRange[0] + ',' + this.dateRange[1];
            }
            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: '/rateAudit',
                path: '/organization',
                query: {
                    // organId: row.organizationId,
                    // rateId: row.id
                    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.length > 0) {
                params.query.status = this.status;
            } else {
                params.query.status = ['ASSIGN_EXPERT', 'SUBMIT_GRADE', 'COLLECT_PAPER_MATERIALS'];
            }

            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);

            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) {
            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: '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: '/organizationExpert',
                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);
                });
        },
        openScore(row) {
            this.dialogScore = true;
            this.scoreInfo = row;
        },
        saveScore() {
            this.scoreInfo.status = 'SUBMIT_PAPER_MATERIALS';
            this.$http
                .post(
                    '/rate/save',
                    {
                        ...this.scoreInfo
                    },
                    { body: 'json' }
                )
                .then(res => {
                    this.$message.success('OK');
                    this.dialogScore = false;
                    // this.scoreInfo = '';
                    this.getData();
                })
                .catch(e => {
                    console.log(e);
                    this.$message.error(e.error);
                });
        },
        saveComplete(row) {
            this.$confirm('确认已收到区文旅局提交的材料?', '提示', {
                confirmButtonText: '已收到',
                cancelButtonText: '暂未收到',
                type: 'warning'
            })
                .then(() => {
                    this.$http
                        .post('/rate/paperMaterial', {
                            id: row.id,
                            status: 'COMPLETE',
                            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);
                });
        }
    }
};
</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;
}
.span-width {
    width: 330px;
    // width: 80%;
    display: inline-block;
    text-align: right;
}
.span-width2 {
    width: 500px;
    // float: left;
    text-align: right;
    display: inline-block;
}
</style>
