<template>
    <div class="assessmentApplication">
        <div class="assessmentApplicationBtn">
            <div class="collectSeach" :style="$utils.collectSeachSty()">
                <div class="exceed">
                    <span class="exceedSpan">申报单号：</span>
                    <el-input v-model="orderNumber" placeholder="请输入申报单号"></el-input>
                </div>
                <div class="exceed">
                    <span class="exceedSpan">填报部门：</span>
                    <el-input v-model="departNameS" placeholder="请输入填报部门"></el-input>
                </div>
                <div class="exceed">
                    <span class="exceedSpan" style="margin-left: 10px;width: 80px">选择时间：</span>
                    <el-date-picker
                        v-model="timeIds"
                        type="month"
                        :clearable="false"
                        value-format="YYYY-MM"
                        placeholder="选择时间"
                    />
                </div>
                <seachs @handleSeach="getSeachData" @handleRest="resetSeach" style="width: 260px"></seachs>
                <el-button size="mini" color="#3B7AD1" icon="Operation" @click="applicationTableFn" style="margin-left: 10px">
                    <span>统计汇总</span>
                </el-button>
            </div>
            <div class="PeriodBtn" :style="$utils.PeriodBtnSty()">
                <btns
                :showImport="false"
                :showExport="false"
                :showSave="false"
                :showAdd="$utils.havePurview('evaluationApplication:oneLevel:add')"
                :showDelete="$utils.havePurview('evaluationApplication:oneLevel:delete')"
                :disDelete="changeDateSelect.length === 0"
                :disImport="true"
                :disExport="true"
                @handleAdd="handleAdd"
                @handleDelete="handleDelete"
                ></btns>
            </div>
            <div class="assessmentApplicationTableData">
                <el-table :data="assessmentApplicationData" style="width: 100%" @select="rowClick" :class="evalApplicationTableSty()"
                 @select-all="rowClick" @row-dblclick="getDetail" @cell-click="clickDes">
                    <el-table-column type="selection" label="操作" align="center"></el-table-column>
                    <el-table-column label="申报单号" prop="orderNumber" width="200"/>
                    <el-table-column label="部门名称" width="300">
                        <template #default="scope">
                            <el-tooltip
                                class="box-item"
                                effect="customized"
                                :content="scope.row.deptName"
                                placement="top"
                            >
                                <span class="tooltipCC">{{scope.row.deptName}}</span>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <!-- <el-table-column label="部门领导" prop="deptLeaderName" /> -->
                    <el-table-column label="评定等级" prop="ratingGrade" />
                    <el-table-column label="申报等级" prop="declarationLevel" />
                    <el-table-column label="申报年度" prop="annual" />
                    <el-table-column label="申报月份" prop="declarationMonth" />
                    <el-table-column label="申报理由" width="300">
                        <template #default="scope">
                            <div v-if="!scope.row.chngeDes">
                                <el-tooltip
                                    class="box-item"
                                    effect="customized"
                                    :content="scope.row.declarationReason"
                                    placement="top"
                                >
                                    <span class="tooltipCC">{{scope.row.declarationReason}}</span>
                                </el-tooltip>
                            </div>
                            <div v-else>
                                <el-input v-model="scope.row.declarationReason" :rows="1" 
                                type="textarea" placeholder="请输入申报理由" @blur="modifyDesFn(scope.row)"></el-input>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="流程状态" prop="stage" width="150">
                        <template #default="scope">
                            <p class="indicitem" @click="seeStates(scope.row)">{{scope.row.stage}}</p>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="200">
                        <template #default="scope">
                            <div style="display:flex">
                                <p class="indicitem" v-if="scope.row.stage === '流程未启动'" @click="agetdeptresponsibility(scope.row)">启动</p>
                                <p style="font-size: 12px;margin-right: 20px;" v-else-if="scope.row.stage === '流程已结束'" >已结束</p>
                                <p style="font-size: 12px;margin-right: 20px;" v-else >已启动</p>
                                <p class="indicitem" v-if="scope.row.stage === '流程已结束'" @click="getGenerateReport(scope.row)">生成报表</p>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="page.currentPage"
                    :page-size="page.pagesize"
                    layout="total, prev, pager, next, jumper"
                    :total="page.total">
                </el-pagination>
            </div>
            <el-dialog :title="title" custom-class="startToDia" v-model="dialogVisible" width="600px" :close-on-click-modal="false">
                <div class="periodFrom">
                    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" :validate-on-rule-change="false">
                        <el-form-item label="部门名称" prop="deptName">
                            <el-select v-model="ruleForm.deptName" placeholder="请选择部门名称" @change="changeDeptLead">
                                <el-option
                                v-for="item in departData"
                                :key="item.deptId"
                                :label="item.deptName"
                                :value="item.deptId">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <!-- <el-form-item label="部门领导"> -->
                            <!-- <el-select v-model="ruleForm.deptLeaderName" placeholder="请选择部门领导"> prop="deptLeaderName"
                                <el-option
                                v-for="item in deptLeaderOption"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                                </el-option>
                            </el-select> -->
                            <!-- <el-input v-model="ruleForm.deptLeaderName" disabled></el-input>
                        </el-form-item> -->
                        <el-form-item label="申报等级" prop="declarationLevel">
                            <el-select v-model="ruleForm.declarationLevel" placeholder="请选择申报等级">
                                <el-option
                                v-for="item in declarationLevelOption"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="申报年份" prop="annual">
                            <el-date-picker
                                v-model="ruleForm.annual"
                                type="year"
                                value-format="YYYY"
                                placeholder="请选择申报年份"
                                />
                        </el-form-item>
                        <el-form-item label="申报月份">
                            <el-input-number v-model="ruleForm.declarationMonth" :min="1" :max="12" />
                        </el-form-item>
                        <el-form-item label="申报理由" prop="declarationReason">
                            <el-input v-model="ruleForm.declarationReason" :rows="5" type="textarea" placeholder="请输入申报理由"></el-input>
                        </el-form-item>
                    </el-form>
                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false">取 消</el-button>
                        <el-button type="primary" @click="saveevaluaStart('ruleForm')">确 定</el-button>
                    </span>
                </template>
            </el-dialog>
            <el-dialog title="流程详情" v-model="statesVisible" :fullscreen="true" :close-on-click-modal="false">
                <div class="flowSty">
                    <iframe id="iframeContain" width="100%" height="500px"
                     frameborder="0" class="iframe" name="iframeContain" seamless scrolling="no" :src="iframeURL">            
                    </iframe>
                    <el-table :data="stageArr" style="width: 100%">
                        <el-table-column type="index" label="序号" align="center" />
                        <el-table-column label="任务名称" prop="taskName" />
                        <el-table-column label="任务创建时间" prop="createTime" />
                        <el-table-column label="任务处理时间" prop="approveTime" />
                        <el-table-column label="候选人" prop="assignInfo" width="300">
                            <template #default="scope">
                                <span>{{changeAssignInfo(scope.row)}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="执行人" prop="approverName" />
                        <el-table-column label="处理状态" prop="status">
                            <template #default="scope">
                                <div v-if="scope.row.status === 'start'">启动</div>
                                <div v-else-if="scope.row.status === 'agree'">同意</div>
                                <div v-else-if="scope.row.status === 'awaiting_check'">等待,待审批</div>
                                <div v-else-if="scope.row.status === 'reject'">驳回</div>
                            </template>
                        </el-table-column>
                        <el-table-column label="备注/意见" prop="opinion" />
                    </el-table>
                </div>
            </el-dialog>
            <el-dialog title="流程启动" v-model="activeVisible" width="600px" :close-on-click-modal="false">
                <div class="periodFrom">
                    <el-form ref="ruleForm" label-width="100px" class="demo-ruleForm" :validate-on-rule-change="false">
                        <el-form-item label="审批领导">
                            <el-select v-model="activeLeaderName" placeholder="请选择审批领导">
                                <el-option
                                v-for="item in leaderArr"
                                :key="item.no"
                                :label="item.userName"
                                :value="item.no">
                                <span style="float: left;display:inline-block;width:100px">{{ item.userName }}</span>
                                <span style="float: right;color: #909399;font-size: 13px;" >{{ item.no }}</span>
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-form>
                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="activeVisible = false">取 消</el-button>
                        <el-button type="primary" @click="activeresponsibility()">启 动</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
        <!-- @approveMsg="approveMsg" -->
        <start-from-list ref="assessmentApplicationDetail" ></start-from-list>
        <application-table ref="applicationTable"></application-table>
    </div>
</template>

<script>
import startFromList from './assessmentApplicationFrom.vue'
import applicationTable from './evaluationApplicationTab.vue'

import btns from '../elbuttonS.vue'
import seachs from '../seachGroup.vue'
import { saveAs } from 'file-saver'
import {apiGetevaluatiodeptadList, apiPostevaluationdeptadSave,apiGetdoAction,apiGetDepartmentLeader,apideptAdmodify,
apiGetworkflowgetOpinion,apiGetevaluationdeptadReport,apiGetEvaluationDeptListAll,apiGetobtainApprovalLeader,
apideptAdState, apiGetparticipantsNumber, apiPostevaluationdeptadDelete, apiGetaddApprovalLeader} from '../../api/api'
export default {
    components: {
        startFromList,
        applicationTable,
        btns,
        seachs
    },
    data() {
        return {
            dialogVisible: false,
            statesVisible: false,
            activeVisible: false,
            title: '',
            activeLeaderName: '',
            windframradio: {},
            deleteSelect: [],
            changeDateSelect: [],
            assessmentApplicationData:[],
            leaderArr: [],
            activeRowObj: {},
            page:{
                pagesize: 12,
                currentPage: 1,
                total: 0
            },
            ruleForm: {
                deptName: '',
                deptLeaderName: '',
                declarationLevel: '',
                annual: '',
                declarationMonth: 1,
                declarationReason: ''
            },
            rules: {
                deptName: [
                    { required: true, message: '请选择部门名称', trigger: 'change' }
                ],
                deptLeaderName: [
                    { required: true, message: '请选择部门领导', trigger: 'change' }
                ],
                declarationLevel: [
                    { required: true, message: '请选择申报等级', trigger: 'change' }
                ],
                annual: [
                    { required: true, message: '请选择申报年份', trigger: 'change' }
                ],
                declarationReason: [
                    { required: true, message: '请输入申报理由', trigger: 'blur' }
                ]
            },
            deptLeaderOption: [],
            declarationLevelOption: [],
            ruleDataAll: [],
            orderNumber: '',
            departNameS: '',
            timeIds: '',
            iframeURL: '',
            stageArr: [],
            departData: [],
            DepartmentLeaderObj: {},
            winPix: window.devicePixelRatio,
            innerWidth: window.innerWidth
        }
    },
    created() {
        this.declarationLevelOption = [
            {
                label: 'A',
                value: 'A'
            },
            {
                label: 'B',
                value: 'B'
            },
            {
                label: 'C',
                value: 'C'
            },
            {
                label: 'D',
                value: 'D'
            }
        ]
        this.getassessmentApplicationList()
        this.getDepartmentFromTreeData()
    },
    methods:{
        // 查询列表页面
        getassessmentApplicationList() {
            let that = this
            let userMes = JSON.parse(window.sessionStorage.getItem('user'))
            let params = {
                pageNum: that.page.currentPage,
                pageSize: that.page.pagesize,
                orderNumber: that.orderNumber,
                deptName: that.departNameS,
                deptId: userMes.deptId,
                // deptId: '',
                annual: that.timeIds ? this.timeIds.substring(0, this.timeIds.indexOf('-'))*1 : null,
                declarationMonth: that.timeIds ? this.timeIds.substring(this.timeIds.indexOf('-')+1, this.timeIds.length)*1 : null
            }
            apiGetevaluatiodeptadList(params).then(datas =>{
                if (datas && datas.data) {
                    that.assessmentApplicationData = datas.data.records
                    that.page.total = datas.data.total
                }
            })
        },
        // 查询部门
        getDepartmentFromTreeData() {
            let that = this
            // let params = {
            //     id: '23031001',
            //     num: 1
            // }
            // apiGetorganizationstructureFromTree(params).then(datas =>{
            //     if (datas && datas.data) {
            //         that.departData = datas.data[0].children
            //     }
            // })
            apiGetEvaluationDeptListAll().then(datas =>{
                if (datas && datas.data) {
                    that.departData = datas.data
                }
            })
        },
        // 根据部门查询人员
        changeDeptLead(val) {
            let that = this
            apiGetDepartmentLeader(val).then(datas =>{
                if (datas && datas.data) {
                    that.DepartmentLeaderObj = datas.data
                    that.ruleForm.deptLeaderName = datas.data.chargePersonName
                }
            })
        },
        applicationTableFn() {
            this.$refs.applicationTable.init(this.departData)
        },
        saveevaluaStart(formName) {
            let that = this
            that.$refs[formName].validate((valid) => {
                if (valid) {
                    that.saveAndEditIndicatorData()
                }
            });
        },
        //新增/修改
        saveAndEditIndicatorData() {
            let that = this
            let userMes = JSON.parse(window.sessionStorage.getItem('user'))
            let deptName = ''
            that.departData.forEach(itv =>{
                if (itv.deptId === that.ruleForm.deptName) {
                    deptName = itv.deptName
                }
            })
            let params = {
                deptId: that.ruleForm.deptName,
                deptName: deptName,
                // deptLeaderId: that.DepartmentLeaderObj.chargePersonId,
                // deptLeaderName: that.ruleForm.deptLeaderName,
                declarationLevel: that.ruleForm.declarationLevel,
                annual: that.ruleForm.annual*1,
                declarationMonth: that.ruleForm.declarationMonth,
                declarationReason: that.ruleForm.declarationReason,
                applicantId: userMes.id,
                applicantName: userMes.name
            }
            if (that.isSave) {
                params.id = that.evalradio.id
            }
            apiPostevaluationdeptadSave(params).then(datas =>{
                if (!datas.success) {
                    that.$message({
                        message: datas.message,
                        type: 'error'
                    });
                } else {
                    if (!that.isSave) {
                        that.$message({
                            message: '绩效结果考核申报信息新增成功',
                            type: 'success'
                        });
                    } else {
                        that.$message({
                            message: '绩效结果考核申报信息修改成功',
                            type: 'success'
                        });
                    }
                    that.dialogVisible = false
                    that.changeDateSelect = []
                    that.getassessmentApplicationList()
                }
            })
        },
        agetdeptresponsibility(row) {
            this.activeRowObj = row
            this.leaderArr = []
            let that = this
            apiGetparticipantsNumber(row.id).then(res =>{
                if (res.success) {
                    that.$message({
                        message: row.annual+'年度'+row.declarationMonth+'月份本次申报人数为'+res.data+'人',
                        type: 'success'
                    });
                    this.activeVisible = true
                    let params = {
                        id: row.deptId
                    }
                    apiGetobtainApprovalLeader(params).then(datas =>{
                        if (datas && datas.data) {
                            that.leaderArr = datas.data
                            if (datas.data.length>0) {
                                that.activeLeaderName = datas.data[0].no
                            }
                        }
                    })
                }
            })
        },
        activeresponsibility() {
            setTimeout(() =>{
                let that = this
                let row = this.activeRowObj
                let pars = {
                    id: row.id,
                    employeeNo: that.activeLeaderName
                }
                apiGetaddApprovalLeader(pars).then(val =>{
                    if (val && val.data) {
                        that.activeVisible = false
                        let par = {
                            defKey: "jxjgkhsb",
                            businessKey: row.id,
                            action: "start",
                            opinion: "绩效结果考核申报",
                            iamCode: window.localStorage.getItem('code')
                        }
                        apiGetdoAction(par).then(datas =>{
                            if (datas && datas.data) {
                                if (!datas.data.isOk) {
                                    that.$message({
                                        message: datas.data.msg,
                                        type: 'error'
                                    });
                                } else {
                                    let params = {
                                        id: row.id,
                                        stage: '流程已开始'
                                    }
                                    apideptAdState(params).then(values =>{
                                        if (values.success) {
                                            that.getassessmentApplicationList()
                                        } else {
                                            that.$message({
                                                message: values.message,
                                                type: 'error'
                                            });
                                        }
                                    })
                                }
                            }
                        })
                    } else {
                        that.$message({
                            message: '领导添加失败',
                            type: 'error'
                        });
                    }
                })
            },100)
        },
        clickDes(row, column, cell, event) {
            if (row.stage === '流程已结束') {
                row.chngeDes = false
            } else {
                let userMes = JSON.parse(window.sessionStorage.getItem('user'))
                if ((userMes.id === row.applicantId && row.stage === '流程未启动') || userMes.deptId === '23031009') {
                    if (column.label === '申报理由') {
                        row.chngeDes = true
                    } else {
                        row.chngeDes = false
                    }
                }
            }
        },
        //明细
        getDetail(row) {
            this.$refs.assessmentApplicationDetail.init(row)
        },
        modifyDesFn(row) {
            let that = this
            let params = {
                id: row.id,
                declarationReason: row.declarationReason
            }
            apideptAdmodify(params).then(datas =>{
                if (!datas.success) {
                    that.$message({
                        message: datas.message,
                        type: 'error'
                    });
                } else {
                    that.$message({
                        message: '绩效结果考核申报申报理由修改成功',
                        type: 'success'
                    });
                    that.getassessmentApplicationList()
                }
            })
        },
        changeAssignInfo(row) {
            let showStr = ''
            if (row.assignInfo) {
                showStr = row.assignInfo.substring(row.assignInfo.indexOf('-')+1, row.assignInfo.length).substring(0, row.assignInfo.substring(row.assignInfo.indexOf('-')+1, row.assignInfo.length).indexOf('-'))
            }
            return showStr
        },
        seeStates(row) {
            if (!row.instId) {
                this.$message({
                    type: 'error',
                    message: '无法查看流程'
                });
            } else {
                this.statesVisible = true
                let url = ''
                if (window.location.hostname === '10.65.78.81') {
                    url = 'http://10.65.79.85:8080'
                } else {
                    url = 'http://10.65.78.23:8080'
                }
                this.iframeURL = url+'/agilebpm-ui/bpm/instance/instanceImageDialog.html?instanceId='+row.instId+'&iamCode='+window.localStorage.getItem('code')
                this.getstageData(row.instId)
            }
        },
        // 根据流程id获取业务id
        getstageData(id) {
            let that = this
            let params = {
                instId: id,
                iamCode: window.localStorage.getItem('code')
            }
            apiGetworkflowgetOpinion(params).then(datas =>{
                if (datas && datas.data) {
                    that.stageArr = datas.data.data                    
                }
            })
        },
        getSeachData() {
            this.page.currentPage = 1
            this.getassessmentApplicationList()
        },
        resetSeach() {
            this.page.currentPage = 1
            this.orderNumber = ''
            this.departNameS = ''
            this.timeIds = ''
            this.getassessmentApplicationList()
        },
        handleSizeChange(val){
            this.page.pagesize = val
            this.getassessmentApplicationList()
        },
        handleCurrentChange(val){
            this.page.currentPage =val
            this.getassessmentApplicationList()
        },
        rowClick(selection, row) {
            this.changeDateSelect = selection
        },
        approveMsg(val) {
            if (val) {
                this.getassessmentApplicationList()
            }
        },
        handleAdd() {
            this.dialogVisible = true
            this.title = '新建表单填报'
            let yearStr = new Date().getFullYear()
            let monthStr = new Date().getMonth()+1
            this.$nextTick(() =>{
                this.$refs['ruleForm'].resetFields()
                this.ruleForm = {
                    deptName: '',
                    deptLeaderName: '',
                    declarationLevel: '',
                    annual: yearStr.toString(),
                    declarationMonth: monthStr,
                    declarationReason: ''
                }
            })
        },
        //删除
        handleDelete() {
            this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let that = this
                let paramsArr = []
                that.changeDateSelect.forEach(it =>{
                    paramsArr.push(it.id)
                })
                apiPostevaluationdeptadDelete(paramsArr.join(',')).then(datas =>{
                    that.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    that.getassessmentApplicationList()
                    that.changeDateSelect = []
                })
            })
        },
        getGenerateReport(row) {
            apiGetevaluationdeptadReport(row.id).then(datas =>{
                let blob = new Blob([datas], { type: "application/vnd.ms-excel" })
                saveAs(blob, '公司本部部门及员工月度绩效考核结果申报表.xlsx')
            })
        },
        evalApplicationTableSty() {
            if (this.winPix === 1.25 || this.innerWidth < 1800) {
                return 'evalApplication125Table'
            } else {
                return 'evalApplication100Table'
            }
        }
    }
}
</script>

<style lang="less">
.assessmentApplication{
    .assessmentApplicationBtn{
        .collectSeach{
            display: flex;
            padding: 24px 20px;
            border-bottom: 1px solid#D6DBEA;
            .exceed{
                display: flex;
                .exceedSpan{
                    width: 105px;
                    height: 12px;
                    font-size: 14px;
                    font-family: Microsoft YaHei;
                    font-weight: 400;
                    color: #8991B0;
                    line-height: 12px;
                    margin-top: 14px;
                }
                .el-input{
                    margin-right:10px;
                    height: 40px;
                    .el-input__inner{
                        height:40px;
                    }
                    .el-input__suffix{
                        .el-select__caret{
                            line-height:30px;
                        }
                    }
                }
            }
            .el-select{
                margin-right:10px;
                .el-input__inner{
                    height:30px;
                }
                .el-input__suffix{
                    .el-select__caret{
                        line-height:30px;
                    }
                }
            }
        }
        span{
            font-size:14px;
        }
        .PeriodBtn{
            display: flex;
            justify-content: flex-end;
            padding: 20px 0;
        }
        .el-button{
            height: 30px;
            // width:100px;
            padding: 0 20px ;
            // padding-top: 8px;
            span{
                margin:0;
            }
        }
        .assessmentApplicationTableData{
            .evalApplication125Table{
                .el-table__body-wrapper{
                    height: 53vh !important;
                }
            }
            .evalApplication100Table{
                .el-table__body-wrapper{
                    height: 60vh !important;
                }
            }
            .el-table{
                .el-input__inner{
                    height: 30px !important;
                }
                .el-radio__label{
                    display: none;
                }
                .tooltipCC{
                    width: 300px;
                    display: inline-block;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }
                .tooltipCCDes{
                    width: 200px;
                    display: inline-block;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }
                .indicitem{
                    color: #409EFF;
                    font-size: 12px;
                    margin-right: 20px;
                    cursor:pointer;
                    &:hover{
                        text-decoration: underline;
                    }
                }
            }
            .el-pagination{
                margin-top: 20px;
                text-align: end;
                position: relative;
            }
        }
        .el-overlay{
            .startToDia{
                .el-dialog__body{
                    padding: 30px 60px 30px 20px !important;
                    .periodFrom{
                        .el-select, .el-input{
                            width: 100%;
                        }
                        .el-input{
                            height: 30px;
                        }
                    }
                    .flowSty{
                        width: 100%;
                        height: 70vh;
                    }
                }
            }
        }
    }
    
}
</style>