<template>
    <div class="list-view">
        <el-table
            :data="categories"
            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="tableHeight1"
            :span-method="objectSpanMethod"
            :summary-method="summaryMethod"
            show-summary
        >
            <el-table-column prop="parentLabel" label="一级指标" min-width="25" align="center">
                <template slot-scope="{ row }">
                    {{ row.parentLabel }}
                    <div>{{ row.parentScore }}分</div>
                </template>
            </el-table-column>
            <!-- <el-table-column prop="parentScore" label="总分" min-width="15"> </el-table-column> -->
            <el-table-column prop="label" label="二级指标" min-width="35" align="center"> </el-table-column>
            <el-table-column prop="sub" label="评定项目和要求" min-width="120" show-overflow-tooltip> </el-table-column>
            <el-table-column prop="score" label="分值" min-width="20" align="center"> </el-table-column>
            <el-table-column prop="score" label="参考分" min-width="20" align="center">
                <template slot-scope="{ row }">
                    {{ getValue(row.value) }}
                </template>
            </el-table-column>
            <el-table-column prop="img" label="图片" min-width="90" width="90" align="center">
                <template slot-scope="{ row }">
                    <div class="imgList" v-if="getImg(row.value).length > 0">
                        <template v-for="(item, index) in getImg(row.value)">
                            <el-image
                                :key="index"
                                style="width: 30px; height: 30px;"
                                :src="item"
                                fit="cover"
                                :preview-src-list="getImg(row.value)"
                            ></el-image>
                        </template>
                    </div>
                </template>
            </el-table-column>

            <el-table-column label="最终评分" align="center" width="120">
                <template slot-scope="{ row }">
                    <span v-if="getExpertScore(row.value)">{{ getExpertScore(row.value) }}</span>
                    <div v-else>
                        <el-input-number
                            style="width:100%"
                            v-model="form[row.value]"
                            size="mini"
                            :min="1"
                            :max="row.score"
                            :step="1"
                        >
                        </el-input-number>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <div style="padding:20px 50px;display:flex" class="fixed-btn">
            <el-button @click="$router.go(-1)">返回</el-button>
            <div style="flex-grow:1"></div>
            <el-button type="danger" v-if="submitList.length !== 0" @click="saveDismiss" :loading="loading">
                退回
            </el-button>
            <el-button type="primary" v-if="submitList.length !== 0" @click="saveExpertScore" :loading="loading">
                最终评分
            </el-button>
        </div>
    </div>
</template>
<script>
import { mapState } from 'vuex';
import expert from '@/mixins/expert';

export default {
    name: 'GradeRuleList',
    mixins: [expert],
    data() {
        return {
            multipleMode: false,
            search: '',
            loading: false,
            downloading: false,
            spanArr: [],
            tableHeight1: 730,
            rateList: [],
            info: {},
            form: {}
        };
    },
    computed: {
        ...mapState(['userInfo']),
        selection() {
            return this.$refs.table.selection.map(i => i.id);
        },
        isEXPERT() {
            let info = [...this.userInfo.authorities].find(item => {
                return item.name === 'ROLE_EXPERT';
            });

            return !!info;
        },
        submitList() {
            return [...this.rateList]
                .filter(item => {
                    return !item.expertScore;
                })
                .map(item => {
                    return {
                        ...item,
                        expertScore: this.form[item.type]
                    };
                });
        }
    },
    mounted() {
        this.getGride();
    },
    methods: {
        saveExpertScore() {
            this.loading = true;
            this.$http
                .post('/rateExpertAudit/batchSave', {
                    audits: JSON.stringify(this.submitList)
                })
                .then(res => {
                    return this.$http.post('/rateExpertAudit/grade', {
                        rateId: this.$route.query.id
                    });
                })
                .then(res => {
                    this.$message.success('评审完成');
                    this.loading = false;
                    this.getGride();
                });
        },
        getGride() {
            this.$http
                .post(
                    '/rateExpertAudit/all',
                    {
                        query: {
                            rateId: this.$route.query.id,
                            size: 30
                        }
                    },
                    { body: 'json' }
                )
                .then(res => {
                    if (!res.empty) {
                        this.rateList = res.content;

                        let form = {};
                        // console.log(this.categories);

                        [...this.categories].forEach(item => {
                            form[item.value] = this.getValue(item.value);
                        });
                        // console.log(form);

                        this.form = form;
                    }
                });
        },
        beforeGetData() {
            return { search: this.search };
        },
        toggleMultipleMode(multipleMode) {
            this.multipleMode = multipleMode;
            if (!multipleMode) {
                this.$refs.table.clearSelection();
            }
        },
        addRow() {
            this.$router.push({
                path: '/gradeRuleEdit',
                query: {
                    ...this.$route.query
                }
            });
        },
        editRow(row) {
            this.$router.push({
                path: '/gradeRuleEdit',
                query: {
                    id: row.id
                }
            });
        },
        download() {
            this.downloading = true;
            this.$axios
                .get('/gradeRule/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);
                });
        },
        deleteRow(row) {
            this.$alert('删除将无法恢复，确认要删除么？', '警告', { type: 'error' })
                .then(() => {
                    return this.$http.post(`/gradeRule/del/${row.id}`);
                })
                .then(() => {
                    this.$message.success('删除成功');
                    this.getData();
                })
                .catch(e => {
                    if (e !== 'cancel') {
                        this.$message.error(e.error);
                    }
                });
        },
        objectSpanMethod({ row, column, rowIndex, columnIndex }) {
            if (columnIndex === 0) {
                if (rowIndex === 0) {
                    return {
                        // 合并第一列（columnIndex === 0），从第2行开始往下2行
                        rowspan: 5,
                        colspan: 1
                    };
                } else if (rowIndex === 5) {
                    return {
                        // 合并第一列（columnIndex === 0），从第2行开始往下2行
                        rowspan: 8,
                        colspan: 1
                    };
                } else if (rowIndex === 13) {
                    return {
                        // 合并第一列（columnIndex === 0），从第2行开始往下2行
                        rowspan: 2,
                        colspan: 1
                    };
                }
                if (rowIndex != 0 || rowIndex != 5 || rowIndex != 13) {
                    return {
                        // 删除第一列（columnIndex === 0），第3、4行单元格
                        rowspan: 0,
                        colspan: 0
                    };
                } else {
                    return {
                        // 除了第一列，其余的不变
                        rowspan: 1,
                        colspan: 1
                    };
                }
            }
        },
        getValue(key) {
            let info = [...this.rateList].find(item => {
                return item.type === key;
            });

            return info ? info.score || 0 : 0;
        },
        getImg(key) {
            let info = [...this.rateList].find(item => {
                return item.type === key;
            });

            return info ? info.img || [] : [];
        },
        getExpertScore(key) {
            let info = [...this.rateList].find(item => {
                return item.type === key;
            });

            // console.log(info);
            return info ? info.expertScore || 0 : 0;
        },
        getInfo(key) {
            let info = [...this.rateList].find(item => {
                return item.type === key;
            });

            return info || {};
        },
        summaryMethod({ columns, data }) {
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '总分';
                    return;
                } else if (index === 3) {
                    sums[index] = data.reduce((total, currentValue) => {
                        return total + currentValue.score;
                    }, 0);
                    return;
                } else if (index === 4) {
                    sums[index] = data.reduce((total, currentValue) => {
                        return total + this.getValue(currentValue.value);
                    }, 0);
                    return;
                } else if (index === 6) {
                    if (this.$route.status == '') {
                        sums[index] = data.reduce((total, currentValue) => {
                            return total + this.getExpertScore(currentValue.value);
                        }, 0);
                    } else {
                        sums[index] = data.reduce((total, currentValue) => {
                            return total + this.form[currentValue.value];
                        }, 0);
                    }

                    return;
                } else {
                    return;
                }
            });

            return sums;
        },
        addScore(row) {
            console.log(row.score);
            let test = /^[1-2]$/;
            if (row.score === 3) {
                test = /^[1-3]$/;
            } else if (row.score === 4) {
                test = /^[1-4]$/;
            } else if (row.score === 5) {
                test = /^[1-5]$/;
            } else if (row.score === 6) {
                test = /^[1-6]$/;
            }
            this.$prompt('请输入评分', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputPattern: test,
                inputErrorMessage: '请输入一个不大于' + row.score + '整数'
            })
                .then(({ value }) => {
                    let info = { ...this.getInfo(row.value) };
                    info.expertScore = value;
                    return this.$http.post('/rateExpertAudit/save', info, { body: 'json' });
                })
                .then(res => {
                    this.$message.success('添加成功');
                    this.getGride();
                })
                .catch(() => {});
        },
        saveDismiss() {
            this.loading = true;
            this.$http
                .post('/rate/offline', {
                    id: this.$route.query.id,
                    status: 'REVIEW_PENDING'
                })
                .then(res => {
                    this.loading = false;
                    this.$message.success('退回成功');
                    this.$router.go(-1);
                })
                .catch(e => {
                    this.loading = false;
                    console.log(e);
                    this.$message.error(e.error);
                });
        }
    }
};
</script>
<style lang="less" scoped>
.list-view {
    height: 798px;
}

.imgList {
    display: flex;
    flex-wrap: wrap;
    .el-image {
        margin-left: 3px;
    }
}

/deep/ .el-table {
    &::before {
        content: none;
    }
}
</style>
