<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true">
                <!-- <el-form-item label="财务核算成本 | 月份选择" style="margin-top:5px;"> -->
                <el-form-item :label="this.$t('Selectmonth')" >
                <el-date-picker size="small" v-model="date" :editable="false" format="yyyy-MM" value-format="yyyy-MM" @change="changeMonth" :clearable="false" type="month" :placeholder="$t('Selectmonth')" style="margin-right: 20px"></el-date-picker>
                <el-link type="primary" :underline="false" @click="audits()" v-if="user.timeType.financeAudit == '1'">{{revaelse}}</el-link>
            </el-form-item>
            <!-- <el-radio-group v-model="radio" @change="switchList" style="margin-left:160px;margin-top:5px;"> -->
            <el-radio-group size="small" v-model="radio" @change="switchList" style="margin-left:150px;margin-top:5px;">
                <el-radio-button :label="$t('lable.allStaff')" >{{$t('lable.allStaff')}}({{allFinanceList.length}})</el-radio-button>
                <el-radio-button :label="$t('projectworker')">{{$t('projectworker')}}({{noReportUserList.length}})</el-radio-button>
            </el-radio-group>
            <el-form-item v-if="permissions.financialProportion" style="margin-left:5px;">
                <el-link type="primary" :underline="false" @click="showSettingDialog()" >{{ $t('Apportionmentratesetting') }}</el-link>
            </el-form-item>

            <el-form-item style="float:right;" v-if="permissions.financialUpload">
                <el-link type="primary" :underline="false" @click="getTemplate()" >{{ $t('Downloadthetemplate') }}</el-link>
            </el-form-item>
            <!-- <el-form-item style="float:right;">
                <el-upload ref="upload" action="#" :limit="1" :http-request="importFinance" :show-file-list="false">
                        <el-link type="primary" :underline="false" >财务数据上传</el-link>
                    </el-upload>
            </el-form-item> -->
            <el-form-item style="float:right;" v-if="permissions.financialUpload">
                <el-link type="primary" :underline="false" @click="importDialog = true;isUploading=false;">{{ $t('Dataupload') }}</el-link>
            </el-form-item>
            <el-form-item style="float:right;" v-if="permissions.financialExport">
                <el-link type="primary" :underline="false" @click="exportDialog = true;exportMonth = date;">{{ $t('Exportdata') }}</el-link>
            </el-form-item>
            <el-form-item style="float:right;" v-if="permissions.financialCustom">
                <el-link type="primary" :underline="false" @click="showItemDialog()">{{ $t('Customizesalaryitems') }}</el-link>
            </el-form-item>
            <el-form-item style="float:right;" v-if="user.timeType.financeAudit == '1' && permissions.setFinanceAuditor">
                <el-link type="primary" :underline="false" @click="reviewerVisible = true">{{ $t('Setupauditor') }}</el-link>
            </el-form-item>
            
            </el-form>
        </el-col>
        <!-- 上传记录 -->
        <el-dialog :title="$t('Salaryuploadrecord')" :visible.sync="xzImportVisible" width="1100px" :before-close="handleClose">
            <div>
                <el-table :data="xzList" style="width: 100%" :height="400">
                    <el-table-column prop="userName" :label="$t('other.operator')">
                        <template slot-scope="scope">
                            <div>
                                <span v-if="user.userNameNeedTranslate == '1'"><ww-open-data type='userName' :openid='scope.row.userName'></ww-open-data></span>
                                <span v-if="user.userNameNeedTranslate != '1'">{{scope.row.userName}}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="ymonth" :label="$t('BelongsIn')"></el-table-column>
                    <el-table-column prop="fileName" :label="$t('filename')">
                        <template slot-scope="scope">
                            <div>
                                <el-link type="primary" @click="downloadByA({name:scope.row.fileName,url:scope.row.serverName})"> {{scope.row.fileName}}</el-link>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="recoverReport" :label="$t('Whetherdailycostiscovered')" width="150">
                        <template slot-scope="scope">
                            <div>
                                {{scope.row.recoverReport == 1? $t('state.yes') : $t('state.no')}}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="recoverMonthcost" :label="$t('Whethermonthlypersonnelcostiscovered')" width="150">
                        <template slot-scope="scope">
                            <div>
                                {{scope.row.recoverMonthcost == 1? $t('state.yes') : $t('state.no')}}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="indate" :label="$t('Uploadtime')"></el-table-column>
                    <!-- <el-table-column prop="date" label="操作" v-if="(tabPosition == 1 || tabPosition == 0) && (reviewerRuleForm.auditorId == user.id || user.role == 1 || user.role == 2)">
                        <template slot-scope="scope">
                            <div>
                                <el-button type="primary" size="small" v-if="tabPosition == 0" @click="operationList(0, scope.row.id)">通过</el-button>
                                <el-button type="warning" size="small" v-if="tabPosition == 0" @click="operationList(1, scope.row.id)">驳回</el-button>
                                <el-button type="warning" size="small" v-if="tabPosition == 1" @click="operationList(2, scope.row.id)">撤销</el-button>
                            </div>
                        </template>
                    </el-table-column> -->
                </el-table>
            </div>
        </el-dialog>
        <!-- 财务报表审核 -->
        <el-dialog :title="shenhe" :visible.sync="importVisible" width="1100px" :before-close="handleClose">
            <div>
                 <el-radio-group v-model="tabPosition" style="margin-bottom: 20px;" @change="operationalData()">
                    <el-radio-button label="1">{{ $t('state.alreadyPassed') }}</el-radio-button>
                    <el-radio-button label="0">{{ $t('state.WaitingAudit') }}</el-radio-button>
                    <el-radio-button label="2">{{ $t('state.rejected') }}</el-radio-button>
                    <el-radio-button label="-1">{{ $t('state.undone') }}</el-radio-button>
                </el-radio-group>
                
                <el-table :data="reviewLis" style="width: 100%" :height="400">
                    <el-table-column prop="userName" :label="$t('other.operator')">
                        <template slot-scope="scope">
                            <div>
                                <span v-if="user.userNameNeedTranslate == '1'"><ww-open-data type='userName' :openid='scope.row.userName'></ww-open-data></span>
                                <span v-if="user.userNameNeedTranslate != '1'">{{scope.row.userName}}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="ymonth" :label="$t('BelongsIn')"></el-table-column>
                    <el-table-column prop="fileName" :label="$t('filename')">
                        <template slot-scope="scope">
                            <div>
                                <el-link type="primary" @click="downloadByA({name:scope.row.fileName,url:scope.row.serverName})"> {{scope.row.fileName}}</el-link>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="recoverReport" :label="$t('Whetherdailycostiscovered')" width="150">
                        <template slot-scope="scope">
                            <div>
                                {{scope.row.recoverReport == 1? $t('state.yes') : $t('state.no')}}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="recoverMonthcost" :label="$t('Whethermonthlypersonnelcostiscovered')" width="150">
                        <template slot-scope="scope">
                            <div>
                                {{scope.row.recoverMonthcost == 1? $t('state.yes') : $t('state.no')}}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="indate" :label="$t('Uploadtime')"></el-table-column>
                    <el-table-column prop="date" :label="$t('operation')" v-if="(tabPosition == 1 || tabPosition == 0) && (reviewerRuleForm.auditorId == user.id)">
                        <template slot-scope="scope">
                            <div>
                                <el-button type="primary" size="small" v-if="tabPosition == 0" @click="operationList(0, scope.row.id)">{{ $t('btn.through') }}</el-button>
                                <el-button type="warning" size="small" v-if="tabPosition == 0" @click="operationList(1, scope.row.id)">{{ $t('btn.rejected') }}</el-button>
                                <el-button type="warning" size="small" v-if="tabPosition == 1" @click="operationList(2, scope.row.id)">{{ $t('btn.undo') }}</el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-dialog>

        <!-- 设置审核人弹窗 -->
        <el-dialog :title="$t('Setupauditor')" :visible.sync="reviewerVisible" width="350px" :before-close="handleCloses">
            <el-form :model="reviewerRuleForm" ref="reviewerRuleForm" label-width="100px" class="demo-ruleForm">
                <el-form-item :label="$t('SelectionofAuditor')" prop="auditorId" :rules="{required: true, message: $t('reviewercannotbeempty'), trigger: 'blur'}">

                    <el-select v-model="reviewerRuleForm.auditorId" clearable :placeholder="$t('SelectionofAuditor')" v-if="user.userNameNeedTranslate != '1'" >
                        <el-option v-for="(item, index) in people" :key="index" :label="item.name" :value="item.id"></el-option>
                    </el-select>

                    <selectCat v-if="user.userNameNeedTranslate == '1'" @selectCal="selectCal" :subject="people" :subjectId="reviewerRuleForm.auditorId" :distinction="'1'" :size="'mini'"></selectCat>

                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitreviewerRuleForm('reviewerRuleForm')">{{ $t('btn.submit') }}</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>


        <el-dialog :title="$t('Exportoffinancialdata')" v-if="exportDialog" :visible.sync="exportDialog" :close-on-click-modal="false" customClass="customWidth" width="400px">
            <el-form ref="form3" >
                <el-form-item :label="$t('Intheexport')" >
                    <!-- <div style="color:orange;">{{date}}</div> -->
                    <el-date-picker v-model="exportMonth" type="month" :placeholder="$t('Selectmonth')" format="yyyy-MM" value-format="yyyy-MM" style="width:280px;"></el-date-picker>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" style="width:100%;" :loading="isUploading" @click="exportFinance">{{ $t('export.export') }}</el-button>
            </div>
        </el-dialog>


        
        <!--列表-->
        <!-- 222 -->
        <el-table :data="list" highlight-current-row v-loading="listLoading" 
        :show-summary='user.timeType.isSecretSalary==0?true:false'
        ref="table"
        :summary-method="getSummaries"
        @selection-change="deleteSel"
        :height="300" style="width: 100%;">
            <el-table-column type="selection" width="80" fixed="left"></el-table-column>
            <el-table-column prop="jobNumber" v-if="user.timeType.financeJobnumEnabled==1" :label="$t('Worknumber')" sortable width="100" fixed="left"></el-table-column>
            <el-table-column prop="name" :label="$t('lable.name')" sortable width="150" fixed="left">
                <template slot-scope="scope">
                    <div>
                        <span v-if="user.userNameNeedTranslate == '1'"><ww-open-data type='userName' :openid='scope.row.name'></ww-open-data></span>
                        <span v-if="user.userNameNeedTranslate != '1'">{{scope.row.name}}</span>
                        <!-- {{scope.row.name}} -->
                    </div>
                </template>
            </el-table-column>
            <template v-if="user.timeType.isSecretSalary==0">
                <el-table-column :prop="headerCols[index]" :label="item" sortable show-overflow-tooltip v-for="(item, index) in tblCols" :key="index" width="130px" align="right">
                <template slot-scope="scope">
                    <div style="padding-right:5px;">{{scope.row[headerCols[index]]==null?'0.00':scope.row[headerCols[index]].toFixed(2)}}</div>
                </template>
                </el-table-column>
            </template>
            <template v-if="user.timeType.isSecretSalary==1">
                <el-table-column :label="item" sortable show-overflow-tooltip v-for="(item, index) in tblCols" :key="index" width="130px" align="center">
                <template slot-scope="scope" >
                    * <span v-if="scope.row"></span>
                </template>
                </el-table-column>
            </template>
            <el-table-column prop="totalCost" width="150" align="right" :label="$t('totalcost')" fixed="right">
                <template slot-scope="scope" >
                    <div style="padding-right:5px;">{{user.timeType.isSecretSalary==0?scope.row.totalCost:'*'}}</div>
                </template>
            </el-table-column>
        </el-table>
        <div style="padding:5px 0 0 10px" v-if="permissions.financialUpload">
            <el-button @click="deleteUsers" size="mini" type="primary" :disabled="deleteSelList.length == 0">{{ $t('Batchdelete') }}</el-button>
        </div>
         
        <el-form :inline="true" >
            <el-form-item >
                <!-- <el-checkbox style="margin-left:10px;" v-model="assignNoProUser" @click="assignToProject">均摊无项目人员成本</el-checkbox> -->
                <!-- <el-button type="primary" :underline="false" size="small" @click="assignNoProUser=false;assignToProject();" style="margin-left:10px;">分摊已填工时人员成本</el-button>
                <el-button type="primary" :underline="false" size="small" @click="assignNoProUser=true;assignToProject();" style="margin-left:10px;">分摊全部人员成本</el-button> -->
                <el-radio-group size="small" v-model="costListRadio" @change="switchCostList" style="margin-left:5px;margin-top:5px;">
                    <el-radio-button label="1" >{{ $t('Apportionmentofpersonnelcosts') }}</el-radio-button>
                    <el-radio-button label="2">{{ $t('Spreadallpersonnelcosts') }}</el-radio-button>
                </el-radio-group>

            </el-form-item>

            <el-form-item style="float:right;margin-right:20px;" v-if="permissions.financialShare">
                <el-link type="primary" :underline="false" @click="uploadTest()" v-if="user.companyId == 936" style="margin-right:10px">上传</el-link>
                <el-link type="primary" :underline="false" @click="exportFinanceDialog=true">{{ $t('ExportingtheAllocationData') }}</el-link>
            </el-form-item>
            
            <!-- <el-form-item style="float:right;margin-right:30px;" v-if="hasNoProjectUsers">
                <el-link type="primary" :underline="false" @click="showNoProjectUsers">查看无项目数据</el-link>
            </el-form-item> -->
        </el-form>
        <!-- 图表 -->
        <!-- <div id="container" :style="'height:300px;width:'+ widthHtval+'px;'"></div> -->
        <div id="clearfix" :style="'overflow-x: auto;width:100%;padding-bottom: 100px; position: relative; height:300px;'">
             <div id="container" :style="'height: 300px;width:100%;'"></div>
        </div>
        <!--新增界面-->
        <el-dialog :title="title" v-if="addFormVisible" :visible.sync="addFormVisible" :close-on-click-modal="false" customClass="customWidth" width="600px">
            <el-form ref="form1" :model="addForm" :rules="rules" label-width="100px">
                <el-form-item :label="$t('Itemno')" >
                    <el-input v-model="addForm.code" :placeholder="$t('Pleaseentertheprojectnumber')" clearable></el-input>
                </el-form-item>
                <el-form-item :label="$t('headerTop.projectName')" prop="name">
                    <el-input v-model="addForm.name" :placeholder="$t('Pleaseenteraprojectname')" clearable></el-input>
                </el-form-item>
                <el-form-item :label="$t('Allparticipants')">
                    <el-select v-model="addForm.userId" multiple filterable :placeholder="$t('Pleaseselectparticipants')" style="width:100%;" @change="changeParticipator">
                        <el-option v-for="item in users" :key="item.id" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('Principalpersoninharge')" >
                    <el-select v-model="addForm.inchargerId" :disabled="addForm.userId.length==0" filterable :placeholder="$t('Pleaseselectthepersonincharge')" style="width:100%;" @change="changeIncharger">
                        <el-option v-for="item in participator" :key="item.id" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="addFormVisible = false">{{ $t('btn.cancel') }}</el-button>
                <el-button type="primary" @click="submitInsert" :loading="addLoading">{{ $t('btn.submit') }}</el-button>
            </div>
        </el-dialog>

        <!--用户详细信息弹出框-->
        <el-dialog :title="$t('Checkthedetails')" v-if="userDetailVisible" :visible.sync="userDetailVisible" :close-on-click-modal="false" customClass="customWidth" width="400px">
            <div class="line"><span>{{ $t('lable.name') }}</span>
                <span v-if="user.userNameNeedTranslate == '1'"><ww-open-data type='userName' :openid='userDetail.name'></ww-open-data></span>
                <span v-if="user.userNameNeedTranslate != '1'">{{userDetail.name}}</span>
            </div>
            <div class="line"><span>{{ $t('Worknumber') }}</span><span>{{userDetail.jobNumber}}</span></div>
            <div class="line"><span>{{ $t('lable.phone') }}</span><span>{{userDetail.phone}}</span></div>
            <div class="line"><span>{{ $t('lable.department') }}</span>
                <span v-if="user.userNameNeedTranslate == '1'"><ww-open-data type='departmentName' :openid='userDetail.departmentName'></ww-open-data></span>
                <span v-if="user.userNameNeedTranslate != '1'">{{userDetail.departmentName}}</span>
            </div>
            <div class="line"><span>{{ $t('costof') }}</span><span>{{userDetail.cost}}{{$t('Yuananhour')}}</span></div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="userDetailVisible = false" >{{ $t('btn.determine') }}</el-button>
            </div>
        </el-dialog>
         
         <!--导入时的设置界面 -->
         <el-dialog :title="$t('Financialdataimport')" v-if="importDialog" :visible.sync="importDialog" :close-on-click-modal="false" customClass="customWidth" width="550px">
            <el-form ref="form3" :model="importParam" >
                <el-form-item :label="$t('Itheimport')" >
                    <!-- <div style="color:orange;">{{date}}</div> -->
                    <el-date-picker v-model="date" type="month" :placeholder="$t('Selectmonth')" format="yyyy-MM" value-format="yyyy-MM"></el-date-picker>
                </el-form-item>
                <el-form-item prop="syncHistoryReport"  >
                    <el-checkbox :label="$t('Recalculatereportedcostsforthemonth')" v-model="importParam.syncHistoryReport"></el-checkbox>
                    <span v-if="user.companyId == '936'">&nbsp;[ 按每月 {{$t(user.timeType.monthDays)}} 天 * 每天 {{$t(user.timeType.allday)}} 小时计算时薪 ]</span>
                </el-form-item>
                <el-form-item prop="syncUserCost"  >
                    <el-checkbox :label="$t('Synchronizeemployeemonthlycosttorganizationalstructure')" v-model="importParam.syncUserCost" ></el-checkbox>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-link v-if="user.timeType.financeAudit == '0'"
                style="float:left;"
                    type="primary" :underline="false" @click="xzjl(),xzImportVisible = true">{{ $t('Viewtheimporthistory') }}</el-link>
            
                <el-upload ref="upload" action="#" :limit="1" :http-request="importFinance" :show-file-list="false" >
                        <el-button type="primary" style="width:100%;" :loading="isUploading" >{{ $t('Selectthefilendstartimporting') }}</el-button>
                    </el-upload>
            </div>
        </el-dialog>

        <!--无项目人员列表-->
        <!-- <el-dialog title="无项目人员列表" v-if="showNPDialog" :visible.sync="showNPDialog" :close-on-click-modal="false" customClass="customWidth" width="1200px">
            <el-table :data="npUserList" highlight-current-row v-loading="listLoading" 
            show-summary=true
            ref="table"
            :height="400" style="width: 100%;">
            <el-table-column prop="name" label="姓名" sortable width="150"></el-table-column>
            <el-table-column prop="monthCost" label="工资"  width="150"></el-table-column>
            <el-table-column prop="bonus" label="奖金" ></el-table-column>
            <el-table-column prop="allowance" label="津贴" ></el-table-column>
            <el-table-column prop="insuranceOld" label="养老保险" ></el-table-column>
            <el-table-column prop="insuranceMedical" label="医疗保险" ></el-table-column>
            <el-table-column prop="insuranceLosejob" label="失业保险" ></el-table-column>
            <el-table-column prop="insuranceInjury" label="工伤保险" ></el-table-column>
            <el-table-column prop="houseFund" label="住房公积金" ></el-table-column>
             <el-table-column prop="others" label="其他" ></el-table-column> 
            <el-table-column :label="item.fieldName" v-for="(item, index) in customCols" :key="item.id" :prop="index==0?'customField1':(index==1?'customField2':(index==2?'customField3':''))">
                <template slot-scope="scope">
                    {{index==0?scope.row.customField1:(index==1?scope.row.customField2:(index==2?scope.row.customField3:''))}}
                </template>
            </el-table-column>
            <el-table-column prop="totalCost" label="总成本" ></el-table-column>
        </el-table>
            <div slot="footer" class="dialog-footer">
                <div style="float:left;color:#ff9900;">*以上人员当月尚无投入的项目，请提醒他们填写日报。</div>
                <el-button type="primary" @click="showNPDialog = false" >关闭</el-button>
            </div>
        </el-dialog> -->

        <el-dialog :title="$t('Customizesalaryitems')" show-header="false" v-if="itemDialog" :visible.sync="itemDialog" :close-on-click-modal="false" customClass="customWidth" width="500px" top="20px">
            <div style="margin-left:30px;">
                <!-- 111 -->
            <p><el-input size="medium" v-model.trim="customCols.monthCost" :placeholder="$t('Pleaseenteracustomsalaryitemname')" style="width:200px;margin-right:20px" maxlength="8"></el-input>
                <template v-if="customCols.monthCost != null && customCols.monthCost != ''">
                {{ $t('Addttotalcost') }} 
                <el-radio size="medium" v-model="customCols.monthCostCalculate" :label="1" style="margin-right:10px;margin-left:10px">{{ $t('state.yes') }}</el-radio>
                <el-radio size="medium" v-model="customCols.monthCostCalculate" :label="0">{{ $t('state.no') }}</el-radio>
                </template>
            </p>
            <p><el-input size="medium" v-model.trim="customCols.bonus" :placeholder="$t('Pleaseenteracustomsalaryitemname')" style="width:200px;margin-right:20px" maxlength="8"></el-input>
                <template v-if="customCols.bonus != null && customCols.bonus != ''">
                {{ $t('Addttotalcost') }} 
                <el-radio size="medium" v-model="customCols.bonusCalculate" :label="1" style="margin-right:10px;margin-left:10px">{{ $t('state.yes') }}</el-radio>
                <el-radio size="medium" v-model="customCols.bonusCalculate" :label="0">{{ $t('state.no') }}</el-radio>
                </template>
            </p>
            <p><el-input size="medium" v-model.trim="customCols.allowance" :placeholder="$t('Pleaseenteracustomsalaryitemname')" style="width:200px;margin-right:20px" maxlength="8"></el-input>
                <template v-if="customCols.allowance != null && customCols.allowance != ''">
                {{ $t('Addttotalcost') }} 
                <el-radio size="medium" v-model="customCols.allowanceCalculate" :label="1" style="margin-right:10px;margin-left:10px">{{ $t('state.yes') }}</el-radio>
                <el-radio size="medium" v-model="customCols.allowanceCalculate" :label="0">{{ $t('state.no') }}</el-radio>
                </template>
            </p>
            <p><el-input size="medium" v-model.trim="customCols.insuranceOld" :placeholder="$t('Pleaseenteracustomsalaryitemname')" style="width:200px;margin-right:20px" maxlength="8"></el-input>
                <template v-if="customCols.insuranceOld != null && customCols.insuranceOld != ''">
                {{ $t('Addttotalcost') }} 
                <el-radio size="medium" v-model="customCols.insuranceOldCalculate" :label="1" style="margin-right:10px;margin-left:10px">{{ $t('state.yes') }}</el-radio>
                <el-radio size="medium" v-model="customCols.insuranceOldCalculate" :label="0">{{ $t('state.no') }}</el-radio>
                </template>
            </p>
            <p><el-input size="medium" v-model.trim="customCols.insuranceMedical" :placeholder="$t('Pleaseenteracustomsalaryitemname')" style="width:200px;margin-right:20px" maxlength="8"></el-input>
                <template v-if="customCols.insuranceMedical != null && customCols.insuranceMedical != ''">
                {{ $t('Addttotalcost') }} 
                <el-radio size="medium" v-model="customCols.insuranceMedicalCalculate" :label="1" style="margin-right:10px;margin-left:10px">{{ $t('state.yes') }}</el-radio>
                <el-radio size="medium" v-model="customCols.insuranceMedicalCalculate" :label="0">{{ $t('state.no') }}</el-radio>
                </template>
            </p>
            <p><el-input size="medium" v-model.trim="customCols.insuranceLosejob" :placeholder="$t('Pleaseenteracustomsalaryitemname')" style="width:200px;margin-right:20px" maxlength="8"></el-input>
                <template v-if="customCols.insuranceLosejob != null && customCols.insuranceLosejob != ''">
                {{ $t('Addttotalcost') }} 
                <el-radio size="medium" v-model="customCols.insuranceLosejobCalculate" :label="1" style="margin-right:10px;margin-left:10px">{{ $t('state.yes') }}</el-radio>
                <el-radio size="medium" v-model="customCols.insuranceLosejobCalculate" :label="0">{{ $t('state.no') }}</el-radio>
                </template>
            </p>
            <p><el-input size="medium" v-model.trim="customCols.insuranceInjury" :placeholder="$t('Pleaseenteracustomsalaryitemname')" style="width:200px;margin-right:20px" maxlength="8"></el-input>
                <template v-if="customCols.insuranceInjury != null && customCols.insuranceInjury != ''">
                {{ $t('Addttotalcost') }} 
                <el-radio size="medium" v-model="customCols.insuranceInjuryCalculate" :label="1" style="margin-right:10px;margin-left:10px">{{ $t('state.yes') }}</el-radio>
                <el-radio size="medium" v-model="customCols.insuranceInjuryCalculate" :label="0">{{ $t('state.no') }}</el-radio>
                </template>
            </p>
            <p><el-input size="medium" v-model.trim="customCols.houseFund" :placeholder="$t('Pleaseenteracustomsalaryitemname')" style="width:200px;margin-right:20px" maxlength="8"></el-input>
                <template v-if="customCols.houseFund != null && customCols.houseFund != ''">
                {{ $t('Addttotalcost') }} 
                <el-radio size="medium" v-model="customCols.houseFundCalculate" :label="1" style="margin-right:10px;margin-left:10px">{{ $t('state.yes') }}</el-radio>
                <el-radio size="medium" v-model="customCols.houseFundCalculate" :label="0">{{ $t('state.no') }}</el-radio>
                </template>
            </p>
            <p><el-input size="medium" v-model.trim="customCols.field1" :placeholder="$t('Pleaseenterthenameofcustomsalaryitem1')" style="width:200px;margin-right:20px" maxlength="8"></el-input>
                <template v-if="customCols.field1 != null && customCols.field1 != ''">
                {{ $t('Addttotalcost') }} 
                <el-radio size="medium" v-model="customCols.field1Calculate" :label="1" style="margin-right:10px;margin-left:10px">{{ $t('state.yes') }}</el-radio>
                <el-radio size="medium" v-model="customCols.field1Calculate" :label="0">{{ $t('state.no') }}</el-radio>
                </template>
            </p>
            <p><el-input size="medium" v-model.trim="customCols.field2" :placeholder="$t('Pleaseenterthenameofcustomsalaryitem2')" style="width:200px;margin-right:20px" maxlength="8"></el-input>
                <template v-if="customCols.field2 != null && customCols.field2 != ''">
                {{ $t('Addttotalcost') }} 
                <el-radio size="medium" v-model="customCols.field2Calculate" :label="1" style="margin-right:10px;margin-left:10px">{{ $t('state.yes') }}</el-radio>
                <el-radio size="medium" v-model="customCols.field2Calculate" :label="0">{{ $t('state.no') }}</el-radio>
                </template>
            </p>
            <p><el-input size="medium" v-model.trim="customCols.field3" :placeholder="$t('Pleaseenterthenameofcustomsalaryitem3')" style="width:200px;margin-right:20px" maxlength="8"></el-input>
                <template v-if="customCols.field3 != null && customCols.field3 != ''">
                {{ $t('Addttotalcost') }} 
                <el-radio size="medium" v-model="customCols.field3Calculate" :label="1" style="margin-right:10px;margin-left:10px">{{ $t('state.yes') }}</el-radio>
                <el-radio size="medium" v-model="customCols.field3Calculate" :label="0">{{ $t('state.no') }}</el-radio>
                </template>
            </p>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="itemDialog = false" >{{ $t('Shutdown') }}</el-button>
                <el-button type="primary" @click="saveItems()" >{{ $t('save') }}</el-button>
            </div>
        </el-dialog>

        <el-dialog :title="date+$t('weekDay.month')+' ' + $t('Noallocationratioofprojectworkinghoursisset')" show-header="false" v-if="settingDialog" :visible.sync="settingDialog" 
        :close-on-click-modal="false" customClass="customWidth" width="1200px">
            <div>
                <div>
                    <el-button :disabled="multipleSelection.length==0" @click="setPercent(true, null)">{{ $t('BatchSettingProportion') }}</el-button>
                    <el-button :disabled="projectCols.length==0 || userCostSettingList.length == 0" @click="getLastMonthSetting">{{ $t('UselastmonthscaleSettings') }}</el-button>
                    <!-- <el-button @click="showSelectProjectDialog">{{date}} 月待分摊项目设置</el-button> -->
                    <el-button @click="showSelectProjectDialog">{{date}}{{ $t('Monthlyprojecttobeapportioned') }}</el-button>
                    <el-button @click="intoAmortizationRatio">{{ $t('Importallocationratio') }}</el-button>
                </div>
                <el-table :data="userCostSettingList" highlight-current-row v-loading="costSettingLoading" 
                     ref="settingTable"  @selection-change="handleSelectionChange" 
                    :height="400" style="width: 100%;">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column prop="name" :label="$t('lable.name')" sortable width="90" fixed="left">
                        <template slot-scope="scope">
                            <div>
                                <span v-if="user.userNameNeedTranslate == '1'"><ww-open-data type='userName' :openid='scope.row.name'></ww-open-data></span>
                                <span v-if="user.userNameNeedTranslate != '1'">{{scope.row.name}}</span>
                            </div>
                        </template>
                    </el-table-column>
                    
                    <el-table-column :label="item.projectName" v-for="(item) in projectCols" width="180" size="small"
                        :key="item.id" align="center">
                        <template slot-scope="scope">
                            <span>{{scope.row[item.projectId]}}</span>%
                        </template>
                    </el-table-column>
                    <el-table-column :label="$t('Settheproportion')"  width="80" fixed="right">
                        <template slot-scope="scope">
                            <el-button size="small" @click="setPercent(false,scope.row)">{{ $t('setup') }}</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="settingDialog = false" >{{ $t('Shutdown') }}</el-button>
                <el-button type="primary" @click="saveMonthSetting()" >{{ $t('save') }}</el-button>
            </div>
        </el-dialog>

        <el-dialog :title="date + $t('projectstobe assessed')" show-header="false" v-if="projectsDialog" :visible.sync="projectsDialog" 
            :close-on-click-modal="false" customClass="customWidth" width="1000px">
            <el-select v-model="chosenProjects" multiple filterable clearable style="width:100%">
                <el-option v-for="item in allProjectList" :label="item.projectName" :key="item.id" :value="item.id"></el-option>
            </el-select>
            <el-checkbox v-model="chosenProjectsChecked" @change="chosenProjectsCheckedClick" style="margin: 20px 0;">{{chosenProjectsChecked ? $t('Deselectallitems') : $t('Selectallitems')}}</el-checkbox>
            <div slot="footer" class="dialog-footer">
                <el-button type="default" @click="projectsDialog = false" >{{ $t('Shutdown') }}</el-button>
                <el-button type="primary" @click="saveProjectSetting()" >{{ $t('btn.determine') }}</el-button>
            </div>
        </el-dialog>
        <el-dialog :title="$t('allocationdata')" v-if="intoAmortizationDialog" :visible.sync="intoAmortizationDialog" customClass="customWidth" width="500px">
            <p>{{'1.' + $t('other.download')}}
            <el-link type="primary" style="margin-left:5px;" :underline="false" :href="'./upload/'+$t('allocationImporttemplates')+'.xlsx'" :download="$t('allocationImporttemplates') + '.xlsx'">{{$t('allocationImporttemplates')+'.xlsx'}}</el-link>
            </p>
            <p>{{'2.' + $t('other.projectsAndPeopleInThetemplate') }}</p>
            <p style="display: flex;justify-content: center;padding:1em 0">
                <el-upload ref="upload"  action="#" :limit="1" :http-request="batchImportData" :show-file-list="false">
                <el-button type="primary" :underline="false" :loading="importingData">{{ $t('other.startImporting') }}</el-button>
            </el-upload>
            </p>
        </el-dialog>
        <el-dialog :title="$t('eachitemofemployeecost')" show-header="false" v-if="setPercentDialog" :visible.sync="setPercentDialog" 
            :close-on-click-modal="false" customClass="customWidth" width="600px" >
            <div style="margin:0px 10px 10px 10px;">
                <span>{{ $t('Selecttheemployee') }}</span>

                <el-select v-if="user.userNameNeedTranslate != '1'" v-model="chosenNoReportUserIds" multiple filterable clearable style="width:330px;" collapse-tags>
                    <el-option v-for="item in noReportUserList" :label="item.name" :key="item.id" :value="item.userId"></el-option>
                </el-select>

                <selectCat v-if="user.userNameNeedTranslate == '1'" @selectCal="selectCal" :subject="noReportUserList" :subjectId="chosenNoReportUserIds" :distinction="'2'" :size="'small'"></selectCat>

                <el-button @click="averageCost" >{{ $t('Automaticallocation') }}</el-button>
            </div>
            <el-divider ></el-divider>
            <!--项目列表 -->
            <el-form v-model="curPercentVal" label-width="365px" style="margin-top:10px;">
                <div class="nameList">
                    <el-form-item v-for="item in projectCols" :label="item.projectName" :key="item.projectId" >
                        {{ $t('Accountedfor') + '：' }}<el-input v-model="curPercentVal[item.projectId]" style="width:100px;" @input="updatePercentValue"></el-input>&nbsp;%
                    </el-form-item>
                </div>
                <el-form-item >
                    {{ $t('totalpercentage') + '：' }}{{totalPercent}}&nbsp;%
                </el-form-item>
            </el-form>
            
            <div slot="footer" class="dialog-footer">
                <el-button type="default" @click="setPercentDialog = false" >{{ $t('Shutdown') }}</el-button>
                <el-button type="primary" @click="setPercentSetting()" >{{ $t('btn.determine') }}</el-button>
            </div>
        </el-dialog>
        <!-- 导入结果说明 -->
        <el-dialog :title="$t('importingtheallocationratio')" v-if="showImportResult" :visible.sync="showImportResult" customClass="customWidth" width="500px">
            <div>
                <span>{{importResultMsg}}</span>
                
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="showImportResult=false">{{ $t('btn.determine') }}</el-button>
            </span>
        </el-dialog>

        <el-dialog :title="$t('AmortizedDataExport')" v-if="exportFinanceDialog" :visible.sync="exportFinanceDialog" :close-on-click-modal="false" customClass="customWidth" width="500px">
            <div style="margin:30px;">
            <el-radio-group v-model="groupByCategory" >
                <el-radio :label="0">{{ $t('Exportbyproject') }}</el-radio>
                <el-radio :label="1">{{ $t('Exportbprojectcategory') }}</el-radio>
            </el-radio-group>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="exportData" :loading="exportDataProcessing" type="primary">{{ $t('export.export') }}</el-button>
            </div>
        </el-dialog>
    </section>
</template>
<style scoped>
.line {
    padding:10px;
}
.line span{
    font-size:18px;
}
.line span:nth-child(even){
    float:right;
}
</style>
<style>
.customWidth .el-dialog__body{
    padding-top: 0;
    padding-bottom: 0;
}
</style>
<script>
import { error } from 'dingtalk-jsapi';
    import util from "../../common/js/util";

// 自定义select组件
    import selectCat from "@/components/select.vue"
    
    export default {
        components: {
            selectCat
        },
        data() {
            return {
                groupByCategory:0,
                exportFinanceDialog:false,
                exportMonth:null,
                exportDialog:false,
                headerCols:['monthCost','bonus', 'allowance', 'insuranceOld', 'insuranceMedical', 'insuranceLosejob', 'insuranceInjury', 'houseFund', 'customField1','customField2','customField3'],
                tblCols:[],
                costListRadio: 0,
                costSettingLoading: false,
                chosenNoReportUserIds:[],
                curPercentVal:{},
                setPercentDialog: false,
                chosenProjects:[],
                projectsDialog: false,
                projectCols:[],
                allProjectList:[],
                multipleSelection:[],
                userCostSettingList: [],
                settingDialog: false,
                radio:this.$t('lable.allStaff'),
                noReportUserList:[],
                allFinanceList:[],
                assignNoProUser: false,
                customFieldList:[],
                itemDialog: false,
                customCols:{},
                customColsi:{},
                // showNPDialog: false,
                npUserList:[],
                hasNoProjectUsers: false,
                isUploading:false,
                importDialog: false,
                importParam:{syncUserCost:true, syncHistoryReport:true},
                user: JSON.parse(sessionStorage.getItem("user")),
                permissions: JSON.parse(sessionStorage.getItem("permissions")),
                userDetailVisible: false,
                userDetail:{},
                date: null,
                tableHeight: 0,
                listLoading: false,
                list: [],

                addLoading: false,
                
                myChart: null,
                params: null,
                totalPercent:0,
                importVisible: false,
                shenhe: '',
                tabPosition: '0',
                reviewerVisible: false,
                reviewerRuleForm: {
                    auditorId: ''
                },
                people: [],
                revaelse: '',
                reviewLis: [],
                ovReviewLis: [],
                xzImportVisible: false,
                xzList: [],
                intoAmortizationDialog : false ,
                importingData: false,
                importResultMsg:null,
                showImportResult:false,
                widthHtval: document.body.clientWidth - 230,
                deleteSelList: [],
                chosenProjectsChecked: false
            };
        },
        methods: {
            uploadTest(){
                this.http.post('/report/uploadThirdReportData',{
                    yearMonth: this.date
                },res => {
                    if(res.code == 'ok'){
                        this.$message({
                            message: '上传成功',
                            type: 'success'
                        })
                    }else{
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        })
                    }
                },err => {
                    this.$message({
                        message: er,
                        type: 'error'
                    })
                })
            },
            chosenProjectsCheckedClick() {
                console.log(this.chosenProjects, '数据')
                if(this.chosenProjectsChecked) {
                    let arr = []
                    for(let i in this.allProjectList) {
                        arr.push(this.allProjectList[i].id)
                    }
                    this.chosenProjects = arr
                } else {
                    this.chosenProjects = []
                }
            },
            deleteSel(sel){
                this.deleteSelList = sel
                // console.log(sel);
            },
            deleteUsers(){
                this.$confirm(this.$t(this.$t('doyouwanttodeleteit')),this.$t('other.prompts'),{
                    confirmButtonText: this.$t('btn.determine'),
                    cancelButtonText: this.$t('btn.cancel'),
                    type: 'warning'
                }).then(()=>{
                    let ids = ''
                    for(let i in this.deleteSelList){
                        ids += this.deleteSelList[i].id + ','
                    }
                    ids = ids.substring(0,ids.length - 1)
                    this.http.post('/finance/batchRemove',{
                        ids: ids
                    },res => {
                        if(res.code == 'ok'){
                            this.getList()
                            this.$message({
                                message: this.$t('message.successfullyDeleted'),
                                type: 'success'
                            })
                            
                        }else {
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            })
                        }
                    },err => {
                        this.$message({
                            message: err,
                            type: 'error'
                        })
                    })
                }).catch(()=>{
                    this.$message({
                        type: 'info',
                        message: this.$t('thedeletionhasbeencancelled')
                    })
                })
                
            },
            exportFinance() {
                this.isUploading = true;
                this.http.post('/finance/exportFinance', {
                    date: this.exportMonth
                },res =>{
                    this.isUploading = false;
                    if(res.code == 'ok') {
                        this.downloadByA({name:this.exportMonth+this.$t('financialdata') + '.xls', url: res.data});
                    }
                },error => {
                    this.$message({
                        message: error,
                        type: "error"
                    });
                })
            },
            arrter() {
                this.http.post('/user/getEmployeeList', {
                    departmentId: '-1',
                    pageIndex: 1,
                    // pageSize: 99999
                    pageSize: -1
                },res =>{
                    if(res.code == 'ok') {
                        this.people = res.data.records
                    }
                },error => {
                    this.$message({
                        message: error,
                        type: "error"
                    });
                })
            },
            addreviewer() {
                this.http.post('/finance-auditor/get', {
                    companyId: this.user.companyId
                },
                    res => {
                        if (res.code == "ok") {
                            // console.log(res.data, '数据')
                            if(res.data) {
                                this.reviewerRuleForm.auditorId = res.data.auditorId
                            } else {
                                this.reviewerRuleForm.auditorId = ''
                            }
                        }
                    },error => {
                        this.$message({
                            message: error,
                            type: "error"
                        });
                    }
                );
            },
            // 提交审核人
            submitreviewerRuleForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.reviewerRuleForm.companyId = this.user.companyId
                        this.http.post('/finance-auditor/save', this.reviewerRuleForm,
                        res =>{
                            if(res.code == 'ok') {
                                this.$message({
                                    message: this.$t('operationissuccessful'),
                                    type: "success"
                                });
                                this.addreviewer()
                            } else {
                                this.$message({
                                    message: this.$t('operationfailure'),
                                    type: "error"
                                });
                            }
                        },error => {
                            this.$message({
                                message: error,
                                type: "error"
                            });
                        })
                        this.reviewerVisible = false
                    } else {
                        return false;
                    }
                });
            },
            handleCloses(done) {
                var formName = 'reviewerRuleForm'
                this.$refs[formName].resetFields();
                done()
            },
            // 审核
            audits() {
                this.shenhe = this.$t('importtheaudits')
                this.importVisible = true
            },
            switchCostList() {
                //已填日报的人员成本
                if (this.costListRadio == 1) {
                    this.assignNoProUser=false;
                    this.assignToProject();
                } else if (this.costListRadio == 2) {
                    //全部人员成本
                    this.assignNoProUser=true;
                    this.assignToProject();
                }
            },
            getLastMonthSetting() {
                this.costSettingLoading = true;
                var dataArr = this.date.split('-');
                var year = dataArr[0];
                var month = dataArr[1];
                if (parseInt(month) == 1) {
                    year = parseInt(year) -1;
                    month = 12;
                } else {
                    month = parseInt(month) -1;
                    if (month < 10) {
                        month = '0'+month;
                    }
                }
                var lastMonth = year + '-' + month;
                this.http.post('/project-percentage/getMonthSetting', {ymonth: lastMonth},
                    res => {
                        this.costSettingLoading = false;
                        if (res.code == "ok") {
                            this.projectCols = res.data.financeProjects;
                            this.allProjectList = res.data.allProjectList;
                            this.userCostSettingList = res.data.userCostSetting;
                            //上次如果没有配置过,需要初始化
                            for (var i=0;i<this.noReportUserList.length; i++) {
                                var rUser = this.noReportUserList[i];
                                //检查当前列表中的无项目人员是否在之前的里面存在，如果不在需要加上去
                                if (this.userCostSettingList.filter(c=>c.id == rUser.userId).length == 0) {
                                    var item = {name: rUser.name, id: rUser.userId};
                                    this.projectCols.forEach(p=>{
                                        item[p.projectId] = 0;
                                    });
                                    this.userCostSettingList.push(item);
                                }
                            }
                            this.$nextTick(()=>{
                                this.$refs.settingTable.doLayout();
                            })
                        } });
            },
            //获取当月的无项目工时人员的分配比例设置
            getMonthSetting() {
                this.costSettingLoading = true;
                this.http.post('/project-percentage/getMonthSetting', {ymonth: this.date},
                    res => {
                        this.costSettingLoading = false;
                        if (res.code == "ok") {
                            this.projectCols = res.data.financeProjects;
                            this.allProjectList = res.data.allProjectList;
                            this.userCostSettingList = res.data.userCostSetting;
                            //上次如果没有配置过,需要初始化
                            for (var i=0;i<this.noReportUserList.length; i++) {
                                var rUser = this.noReportUserList[i];
                                // console.log('userId====='+rUser.userId);
                                //检查当前列表中的无项目人员是否在之前的里面存在，如果不在需要加上去
                                if (this.userCostSettingList.filter(c=>c.id == rUser.userId).length == 0) {
                                    var item = {name: rUser.name, id: rUser.userId};
                                    this.projectCols.forEach(p=>{
                                        item[p.projectId] = 0;
                                    });
                                    this.userCostSettingList.push(item);
                                }
                            }
                            this.$nextTick(()=>{
                                this.$refs.settingTable.doLayout();
                            })
                        } });
            },
            //提交无工时人员的分配设置
            saveMonthSetting() {
                //检查数据是否都分配到100%了，防止由于修改了项目列而导致之前的数据不正确的情况
                var errorList = this.userCostSettingList.filter(u=>{
                    let totalPercent = 0.0;
                    this.projectCols.forEach(p=>{
                        totalPercent += parseFloat(u[p.projectId]);
                    });
                    totalPercent = totalPercent.toFixed(1);
                    if (totalPercent != 100) {
                        return true;
                    } else {
                        return false;
                    }
                });
                if (errorList.length > 0) {
                    var nameList = errorList.map(e=>e.name);
                    this.$message({type:'error', message:this.$t('proportionofassignedpersonnelisnot ')+'100%：'+nameList});
                    return;
                }
                this.http.post('/project-percentage/saveMonthSetting', {projectCols: JSON.stringify(this.projectCols),
                            ymonth: this.date, userSettings: JSON.stringify(this.userCostSettingList)},
                    res => {
                        if (res.code == "ok") {
                            this.$message({type:'success', message:this.$t('savesuccess')});
                            this.settingDialog = false;
                        } else {
                            this.$message({type:'error', message:this.$t('erroroccurred')+':'+res.msg});
                        }});
            },
            updatePercentValue() {
                var total = 0.0;
                this.projectCols.forEach(p=>{
                    total += parseFloat(this.curPercentVal[p.projectId]);
                })
                this.totalPercent = total.toFixed(1);
                this.$forceUpdate();
            },
            averageCost() {
                var avg = (100/this.projectCols.length).toFixed(1);
                //最后一个用100减去前面的总和，保证最终合计为100
                for (var i=0;i<this.projectCols.length; i++) {
                    if (i < this.projectCols.length -1) {
                        this.curPercentVal[this.projectCols[i].projectId] = avg;
                    } else {
                        this.curPercentVal[this.projectCols[i].projectId] = (100-avg*(this.projectCols.length-1)).toFixed(1);
                    }
                }
                this.updatePercentValue();
                this.$forceUpdate();
            },
            setPercent(isBatch, row) {
                this.setPercentDialog = true;
                this.chosenNoReportUserIds = [];
                if (!isBatch) {
                    this.chosenNoReportUserIds.push(row.id);
                    //获取当前比例
                    this.projectCols.forEach(p=>{
                        this.curPercentVal[p.projectId] = row[p.projectId];
                    });
                } else {
                    //批量处理
                    this.multipleSelection.forEach(m=>{
                        this.chosenNoReportUserIds.push(m.id);
                    })
                    //批量时获取第一条的比例进行加载
                    this.projectCols.forEach(p=>{
                        this.curPercentVal[p.projectId] = this.multipleSelection[0][p.projectId];
                    });
                }
                this.updatePercentValue();
            },
            //确认设置的项目列
            saveProjectSetting() {
                this.projectsDialog = false;
                this.projectCols = [];
                this.chosenProjects.forEach(c=>{
                    var item = this.allProjectList.filter(a=>a.id == c)[0];
                    this.projectCols.push({projectId: item.id, projectName: item.projectName, projectCode: item.projectCode});
                });
                
                this.$nextTick(()=>{
                    this.$refs.settingTable.doLayout();
                })
            },
            handleProjectSelectionChange(val) {
                this.projectSelection = val;
            },
            showSelectProjectDialog() {
                //设置选中状态
                this.chosenProjects = [];
                this.chosenProjectsChecked = false
                this.projectCols.forEach(item=>{
                    this.chosenProjects.push(item.projectId);
                })
                this.projectsDialog = true;
            },
            setPercentSetting() {
                //检测是否填写的情况下，是否达到100%
                if (this.totalPercent != 100) {
                    this.$message({
                            message: this.$t('sumoftheallocationsmustbe'),
                            type: "error"
                            });
                    return;
                }

                this.setPercentDialog = false;
                this.chosenNoReportUserIds.forEach(u=>{
                    var targetU = this.userCostSettingList.filter(a=>a.id == u)[0];
                    
                    //遍历项目
                    this.projectCols.forEach(p=>{
                        targetU[p.projectId] = this.curPercentVal[p.projectId];
                    })
                });
                this.userCostSettingList.splice(1,0);
                
            },
            showSettingDialog() {
                this.settingDialog = true;
                this.getMonthSetting();
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            switchList() {
                if (this.radio == this.$t('lable.allStaff')) {
                    this.list = this.allFinanceList;
                } else {
                    this.list = this.noReportUserList;
                }
            },
            downloadByA(row) {
                const a = document.createElement('a'); // 创建a标签
                a.setAttribute('download', row.name);// download属性
                // console.log(row.url);
                if (row.url.indexOf('upload/') == -1) {
                    row.url = '/upload/' +row.url;
                }
                a.setAttribute('href', row.url);// href链接
                a.click();// 自执行点击事件
                a.remove();
            },
            getTemplate() {
                this.http.post('/finance/getTemplate', {companyId: this.user.companyId},
                    res => {
                        if (res.code == "ok") {
                            if (res.data.indexOf('xlsx') > 0) {
                                this.downloadByA({name:this.$t('financialcoststatement')+ '.xlsx', url:res.data});
                            } else {
                                this.downloadByA({name:this.$t('financialcoststatement')+ '.xls', url:res.data});
                            }
                        }});
               
            },
            saveItems() {
            //     let savefields = {
            //         monthCost : this.customCols.monthCost,
            //         bonus : this.customCols.bonus,
            //         allowance : this.customCols.allowance,
            //         insuranceOld : this.customCols.insuranceOld,
            //         insuranceMedical : this.customCols.insuranceMedical,
            //         insuranceLosejob : this.customCols.insuranceLosejob,
            //         insuranceInjury : this.customCols.insuranceInjury,
            //         houseFund : this.customCols.houseFund,
            //         field1 : this.customCols.field1,
            //         field2 : this.customCols.field2,
            //         field3 : this.customCols.field3
            // }
            if(this.customCols.field1 != null && this.customCols.field1 != ''){
                if(this.customCols.field1Calculate == null){
                    this.$message({
                        message: this.$t('choosewhethertoincludethetotalcost'),
                        type: 'warning'
                    })
                    return
                }
            }
            if(this.customCols.field2 != null && this.customCols.field2 != ''){
                if(this.customCols.field1Calculate == null){
                    this.$message({
                        message: this.$t('choosewhethertoincludethetotalcost'),
                        type: 'warning'
                    })
                    return
                }
            }
            if(this.customCols.field3 != null && this.customCols.field3 != ''){
                if(this.customCols.field1Calculate == null){
                    this.$message({
                        message: this.$t('choosewhethertoincludethetotalcost'),
                        type: 'warning'
                    })
                    return
                }
            }
                this.http.post('/finance-tblcuscol/save', this.customCols,
                    res => {
                        if (res.code == "ok") {
                             this.itemDialog = false;
                            this.getCustomColumn();
                        }});
               this.$forceUpdate();
            },
            showItemDialog() {
                // console.log(this.customColsi, '后台纯的')
                // console.log(this.customCols, '用来编辑的')
                this.customCols = JSON.parse(JSON.stringify(this.customColsi))
                // console.log(this.customColsi, '后台纯的')
                // console.log(this.customCols, '用来编辑的')
                this.itemDialog = true;
                // this.customFieldList = {field1:null,field2:null, field3:null};
                // if (this.customCols.field1 !== undefined) {
                //     this.customFieldList.field1 = this.customCols.field1;
                // } else if (this.customCols.field2 !== undefined) {
                //     this.customFieldList.field2 = this.customCols.field2;
                // } else if (this.customCols.field3 !== undefined) {
                //     this.customFieldList.field3 = this.customCols.field3;
                // }
                
                
            },
            //获取自定义的字段
            getCustomColumn() {
                this.http.post('/finance-tblcuscol/getAll', {companyId: this.user.companyId},
                    res => {
                        if (res.code == "ok") {
                            // console.log("获取自定义字段",res.data);
                            this.customColsi = res.data;
                            this.tblCols = [];
                            this.tblCols.push(this.customColsi.monthCost);
                            this.tblCols.push(this.customColsi.bonus);
                            this.tblCols.push(this.customColsi.allowance);
                            this.tblCols.push(this.customColsi.insuranceOld);
                            this.tblCols.push(this.customColsi.insuranceMedical);
                            this.tblCols.push(this.customColsi.insuranceLosejob);
                            this.tblCols.push(this.customColsi.insuranceInjury);
                            this.tblCols.push(this.customColsi.houseFund);
                            if (this.customColsi.field1 != null) {
                                this.tblCols.push(this.customColsi.field1);
                            }
                            if (this.customColsi.field2 != null) {
                                this.tblCols.push(this.customColsi.field2);
                            }
                            if (this.customColsi.field3 != null) {
                                this.tblCols.push(this.customColsi.field3);
                            }
                        }});
                    
            },
            

            // },
            // getProjects() {
            //     this.http.post('/finance/getProjects', {companyId: this.user.companyId, yearMonth: this.date},
            //         res => {
            //             if (res.code == "ok") {
            //                 this.projectCols = res.data.financeProjects;
            //                 this.allProjectList = res.data.allProjectList;
            //             }});
                
            // },
            // showNoProjectUsers() {
            //     this.showNPDialog = true;
            //     this.http.post('/finance/getNoProjectUsers', {yearMonth: this.date},
            //     res => {
            //         if (res.code == "ok") {
            //             this.npUserList = res.data;
            //         }});
            // },
            assignToProject(){
                var _this = this;
                this.http.post('/finance/getTimeCost', {yearMonth: this.date, assignNoProUser: this.assignNoProUser},
                res => {
                    if (res.code == "ok") {

                        for(var i in res.data.costList) {
                            if(i>20) {
                                this.widthHtval = +this.widthHtval + 40
                            } else {
                                this.widthHtval = document.body.clientWidth - 230
                            }
                        }

                        // console.log(res.data, '图表数据', this.widthHtval)

                        var xList = [], yList = [], list = res.data.costList, 
                        
                        totalMoneyCost = res.data.totalMoneyCost;
                        var nopCost = 0;
                        if (res.data.noProjectItem.project != null) {
                            this.hasNoProjectUsers = true;
                            nopCost = res.data.noProjectItem.cost;
                        } else {
                            this.hasNoProjectUsers = false;
                        }
                        
                        for(var i in list) {
                            xList.push(list[i].project);
                            
                            yList.push({
                                "value": list[i].cost,
                                "id": list[i].id,
                                "time": list[i].workingTime
                            });
                        }

                        var myChart = echarts.init(document.getElementById("container"));
                        // 设置图表
                        myChart.resize({
                            width: this.widthHtval
                        })
                        _this.myChart = myChart;
                        var option = {
                            title: {
                                text: _this.assignNoProUser ? _this.$t('costintotal') + totalMoneyCost + _this.$t('yuan')
                                    +(_this.hasNoProjectUsers?"，"+ _this.$t('projectpersonnelcostincluded') + nopCost + _this.$t('yuan'):"")
                                    : _this.$t('costintotal') + totalMoneyCost + _this.$t('yuan'),
                                left:'left',
                            },
                            grid : {
                                top : 40,    //距离容器上边界40像素
                                // bottom: 100,   //距离容器下边界30像素
                                bottom: 40,   //距离容器下边界30像素
                                left: 100,
                                right: 100
                            },
                            // 工具箱
                            toolbox: {
                                show: true,
                                feature:{
                                    saveAsImage:{
                                        show:true
                                    },
                                    restore:{
                                        show:true
                                    },
                                    magicType:{
                                        type:['line','bar']
                                    },
                                     
                                }
                            },
                            tooltip:{
                                trigger:'axis',
                                formatter: function (params,ticket,callback) {
                                    var res = params[0].name + "<br/>"+ _this.$t('workcost')+" : " + params[0].data.value 
                                    + _this.$t('yuan')+"<br/>"+ _this.$t('screening.workTime')+" : " + params[0].data.time + _this.$t('time.hour');
                                    _this.params = params;
                                    return res;
                                }
                            },
                            xAxis: {
                                data: xList,
                                axisLabel: {
                                    interval:0,rotate:20
                                }
                            },
                            yAxis: [{
                                type : 'value',
                                axisLabel: {
                                    formatter:'{value} ('+ _this.$t('yuan')+')'
                                }
                            }],
                            series: [{
                                name: _this.$t('screening.workTime')+'（h）',
                                type: 'bar',
                                barMaxWidth: 30,
                                data: yList,
                            }]
                        };
                        option && myChart.setOption(option,{notMerge: true});
                        // myChart.getZr().on('click', params => {
                        //     const pointInPixel = [params.offsetX, params.offsetY];
                        //     if (myChart.containPixel('grid', pointInPixel)) {
                        //         console.log(_this.params)
                        //         if(_this.radio=='项目') {
                        //             _this.$router.push("/cost/" + _this.params[0].data.id + "/" + _this.params[0].name);
                        //         }
                        //     }
                        // });
                    } else {
                        this.$message({
                            message: res.msg,
                            type: "error"
                        });
                    }
                },
                error => {
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },
            //导出财务数据
            exportData() {
                this.exportDataProcessing = true;
                this.http.post('/finance/exportData', {
                    date: this.date, assignNoProUser: this.assignNoProUser, groupByCategory: this.groupByCategory
                },
                res => {
                    this.exportDataProcessing = false;
                    if (res.code == "ok") {
                        this.exportFinanceDialog = false;
                        var aTag = document.createElement('a');
                        aTag.download = this.$t('financialcoststatisticss')+".xls";
                        aTag.href = res.data;
                        aTag.click();
                    } else {
                        this.$message({
                        message: res.msg,
                        type: "error"
                        });
                    }
                },
                error => {
                    this.listLoading = false;
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },
            getSummaries(param) {
                const { columns, data } = param;
                const sums = [];
                columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = this.$t('zongjia');
                    return;
                }
                if (index === 1){
                    sums[index] = '';
                    return
                }
                if (index === 2 && this.user.timeType.financeJobnumEnabled == 1) {
                    sums[index] = '';
                    return;
                }
                const values = data.map(item => Number(item[column.property]));
                if (!values.every(value => isNaN(value))) {
                    sums[index] = values.reduce((prev, curr) => {
                    const value = Number(curr);
                    if (!isNaN(value)) {
                        return prev + curr;
                    } else {
                        return prev;
                    }
                    }, 0);
                    sums[index] = sums[index].toFixed(2) + this.$t('yuan');
                } else {
                    sums[index] = 'N/A';
                }
                });

                return sums;
            },
            changeMonth() {
                //改变月份
                this.getList();
                this.assignToProject();
                this.getMonths()
            },
            // 批量导入人员
            importFinance(item) {
                //首先判断文件类型
                let str = item.file.name.split(".");
                let format = str[str.length - 1];
                if (format != "xls" && format != "xlsx") {
                    this.$message({
                        message: this.$t('other.PleaseselecttheXLSorXLSXfile'),
                        type: "error"
                    });
                } else {
                    this.listLoading = true;
                    let formData = new FormData();
                    formData.append("file", item.file);
                    formData.append("companyId", this.user.companyId);
                    formData.append("yearMonth", this.date);
                    formData.append("syncUserCost", this.importParam.syncUserCost);
                    formData.append("syncHistoryReport", this.importParam.syncHistoryReport);
                    this.isUploading = true;
                    let urls = ''
                    if(this.user.timeType.financeAudit == '1') {
                        urls = '/finance-import/submitImport'
                    } else {
                        urls = '/finance/importData'
                    }
                    // this.http.uploadFile('/finance/importData', formData,
                    this.http.uploadFile(urls, formData,
                    res => {
                        // console.log(this.user.timeType.financeAudit, '看看数据')
                        this.$refs.upload.clearFiles();
                        this.listLoading = false;
                        this.isUploading = false;
                        if (res.code == "ok") {
                            if (this.user.timeType.financeAudit == 1 ) {
                                this.$message({
                                    message: this.$t('waiforverification'),
                                    type: "warning"
                                });
                                this.getMonths();
                            } else {
                                this.$message({
                                    message: this.$t('other.importSuccess'),
                                    type: "success"
                                });
                            }
                            
                            this.importDialog = false;
                            //重新读取列表
                            this.getList();
                        } else {
                            this.$message({
                                message: res.msg,
                                type: "error"
                            });
                        }
                    },
                    error => {
                        this.$refs.upload.clearFiles();
                        this.listLoading = false;
                        this.$message({
                            message: error,
                            type: "error"
                        });
                    });
                }
            },
            // 导入提交审核
            // submitReview(formData) {
            //     this.http.uploadFile(' /finance-import/submitImport', formData,
            //     res => {
            //         if (res.code == "ok") {
            //             console.log(res.data, '来的数据')
            //         } else {
            //             this.$message({
            //                 message: res.msg,
            //                 type: "error"
            //             });
            //         }
            //     },
            //     error => {
            //         this.$refs.upload.clearFiles();
            //         this.listLoading = false;
            //         this.$message({
            //             message: error,
            //             type: "error"
            //         });
            //     });
            // },

            
            //获取项目列表
            getList() {
                this.listLoading = true;
                this.http.post('/finance/getByMonth', {
                    companyId: this.user.companyId,
                    yearMonth: this.date
                },
                res => {
                    this.listLoading = false;
                    if (res.code == "ok") {
                        var list = res.data;
                        this.allFinanceList = list;
                        
                        this.noReportUserList = list.filter(r=>r.hasReport == 0);
                        if(this.radio == this.$t('lable.allStaff')){
                            this.list = this.allFinanceList;
                        }else{
                            this.list = this.noReportUserList
                        }
                        

                    } else {
                        this.$message({
                        message: res.msg,
                        type: "error"
                        });
                    }
                },
                error => {
                    this.listLoading = false;
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },
            // 获取当月的审核状态
            getMonths() {
                this.http.post('/finance-import/getStatus', {
                    companyId: this.user.companyId,
                    yearMonth: this.date
                },
                res => {
                    this.listLoading = false;
                    if (res.code == "ok") {
                        // console.log(res.data, '审核状态')
                        if(res.data) {
                            if(res.data.state == '0') {
                                this.revaelse = this.$t('state.WaitingAudit')
                                this.tabPosition = '0'
                            } else if(res.data.state == '1') {
                                this.revaelse = this.$t('Auditrecords')
                                this.tabPosition = '1'
                            }else if (res.data.state == '2') {
                                this.revaelse = this.$t('state.rejected')
                                this.tabPosition = '2'
                            } else if (res.data.state == '3') {
                                this.revaelse = this.$t('state.undone')
                                this.tabPosition = '-1'
                            }
                            this.getReviewList()
                        } else {
                            this.revaelse = ''
                        }
                        
                    } else {
                        this.$message({
                            message: res.msg,
                            type: "error"
                        });
                    }
                },
                error => {
                    this.listLoading = false;
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },
            // 获取审核列表
            getReviewList() {
                this.http.post('/finance-import/list', {
                    companyId: this.user.companyId,
                },
                res => {
                    if (res.code == "ok") {
                    //    console.log(res.data, '拿到的数据')
                       this.ovReviewLis = res.data
                       if(this.tabPosition == 0) {
                           this.reviewLis = res.data.pendingList
                       } else if(this.tabPosition == 1) {
                           this.reviewLis = res.data.passList
                       } else if(this.tabPosition == 2) {
                           this.reviewLis = res.data.rejectList
                       } else {
                           this.reviewLis = res.data.cancelList
                       }
                    //    console.log(this.reviewLis, '数据')
                    } else {
                        this.$message({
                            message: res.msg,
                            type: "error"
                        });
                    }
                },
                error => {
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },
            // 操作数据
            operationalData () {
                var sss = this.ovReviewLis
                if(this.tabPosition == 0) {
                    this.reviewLis = sss.pendingList
                } else if(this.tabPosition == 1) {
                    this.reviewLis = sss.passList
                } else if(this.tabPosition == 2) {
                    this.reviewLis = sss.rejectList
                } else {
                    this.reviewLis = sss.cancelList
                }
                // console.log(this.reviewLis, '数据')
            },
            // 审核操作
            operationList(zhi, id) {
                let urls
                if(zhi == 0) {
                    urls = '/finance-import/agree'
                } else if(zhi == 1){
                    urls = '/finance-import/deny'
                } else {
                    urls = '/finance-import/cancel'
                }
                this.http.post(urls, {
                    id: id,
                },
                res => {
                    if (res.code == "ok") {
                       this.$message({
                            message: this.$t('operationissuccessful'),
                            type: "success"
                        });
                        this.getReviewList()
                    } else {
                        this.$message({
                            message: res.msg,
                            type: "error"
                        });
                    }
                },
                error => {
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },
            // 获取薪资上传记录
            xzjl() {
                this.http.post('/finance-import/list', {
                    companyId: this.user.companyId,
                    // pageIndex:1,
                    // pageSize: 9999
                },
                res => {
                    if (res.code == "ok") {
                    //    console.log('123',res.data)
                       this.xzList = res.data.passList
                    } else {
                        this.$message({
                            message: res.msg,
                            type: "error"
                        });
                    }
                },
                error => {
                    this.$message({
                        message: error,
                        type: "error"
                    });
                });
            },
            //导入分摊比例
            intoAmortizationRatio(){
                this.intoAmortizationDialog = true;
            },
            batchImportData(item) {
                //首先判断文件类型
                let str = item.file.name.split(".");
                let format = str[str.length - 1];
                if (format != "xls" && format != "xlsx") {
                    this.$message({
                        message: this.$t('other.PleaseselecttheXLSorXLSXfile'),
                        type: "error"
                    });
                } else {
                    this.importingData = true;
                    let formData = new FormData();
                    formData.append("file", item.file);
                    formData.append("companyId", this.user.companyId);
                    formData.append('ymonth',this.date)
                    this.http.uploadFile('/project-percentage/importData', formData,
                    res => {
                        this.$refs.upload.clearFiles();
                        this.importingData = false;
                        this.showImportResult = true;
                        if (res.code == "ok") {
                            //换成弹出框，以免有人等了半天回来啥也没看到
                            this.importResultMsg = this.$t('other.importSuccess')+res.data+this.$t('apportionmentratiodata')+'。'+(res.msg?res.msg:"");
                            this.showSettingDialog();
                        } else {
                            this.importResultMsg = this.$t('export.Importfailure')+"："+res.msg;
                        }
                    },
                    error => {
                        this.$refs.upload.clearFiles();
                        this.importingData = false;
                        this.$message({
                            message: error,
                            type: "error"
                        });
                    });
                }
            },
            // 左右滚动
            scrollFunction () {
                this.domObj = document.getElementById('clearfix') // 通过id获取要设置的div
                if (this.domObj.attachEvent) { // IE
                this.domObj.attachEvent('onmousewheel', this.mouseScroll)
                } else if (this.domObj.addEventListener) {
                this.domObj.addEventListener('DOMMouseScroll', this.mouseScroll, false)
                }
                this.domObj.onmousewheel = this.domObj.onmousewheel = this.mouseScroll
            },

            mouseScroll(event) { // google 浏览器下
                let detail = event.wheelDelta || event.detail
                let moveForwardStep = -1
                let moveBackStep = 1
                let step = 0
                step = detail > 0 ? moveForwardStep * 100 : moveBackStep * 100
                event.preventDefault() // 阻止浏览器默认事件
                this.domObj.scrollLeft = this.domObj.scrollLeft + step
            },
            // 自定义组件事件
            selectCal(obj) {
                if(obj.distinction == '1') {
                    this.reviewerRuleForm.auditorId = obj.id
                } else if(obj.distinction == '2') {
                    this.chosenNoReportUserIds = obj.id
                }
            }

        },
        created() {
            var d = new Date();
            this.date = d.getFullYear() +'-'+ ((d.getMonth()+1) < 10? '0'+(d.getMonth()+1):d.getMonth()+1);
            
        },
        mounted() {
            let height = window.innerHeight;
            this.tableHeight = height - 245;
            const that = this;
            window.onresize = function temp() {
                that.tableHeight = window.innerHeight - 245;
            };
            
            this.getCustomColumn();
            this.getList();
            // this.getProjects();
            this.addreviewer();
            this.arrter()
            this.getMonths()
            this.scrollFunction()
        },
        updated() {
            this.$nextTick(() => {
                this.$refs['table'].doLayout();
            }) 
        }
    };
</script>

<style lang="scss" scoped>
.nameList {
    height: 400px;
    overflow: auto;
}
</style>