<template>
    <div class="app-container">
    <el-row :gutter="5">
    <el-col :span="22" :xs="24">
        <el-card>
          <div slot="header" class="clearfix">
            <span>查询收入</span>
          </div>
          <div class="date">
            <span style="padding-left:4%">本机日期：</span><span>{{SystemDate}}</span>
            <span style="padding-left:2%">服务器日期：</span><span>{{ServerDate}}</span>
            <span style="padding-left:2%">所属单元：</span><span>{{user.deptId.slice(0,5)}}</span>
          </div>
          <div class="form">
                <el-form :rules="rules" ref="form" inline :model="form" label-width="100px" style="width:100%">
                <el-form-item label="起止月份：" prop="yearMonth">
                        <el-date-picker
                          v-model="form.yearMonth"
                          type="monthrange"
                          value-format="yyyyMM"
                          range-separator="至"
                          start-placeholder="开始月份"
                          end-placeholder="结束月份">
                        </el-date-picker>
                </el-form-item>
                <el-button type="primary" icon="el-icon-search" :loading="searchLoading" @click="getSalaryInfo('form')">&nbsp;查询&nbsp;</el-button>
                <el-button type="primary" icon="el-icon-document" @click="exportExcel" :loading="exportLoading">&nbsp;导出&nbsp;</el-button>
              </el-form>
                <el-table
                  :data="Salary.slice((currentPage-1)*pagesize,currentPage*pagesize)"
                  v-loading = "loading"
                  style="width: 100%">
                    <el-table-column type="expand">
                      <template slot-scope="props">
                        <el-form label-position="left" inline class="demo-table-expand">
                          <el-form-item label="甲方全称">
                            <span>{{ props.row.firstParty }}</span>
                          </el-form-item>
                          <el-form-item label="乙方全称">
                            <span>{{ props.row.secondParty }}</span>
                          </el-form-item>
                          <el-form-item label="项目名称">
                            <span>{{ props.row.projectFullName }}</span>
                          </el-form-item>
                          <el-form-item label="项目内容概要">
                            <span>{{ props.row.projectContent }}</span>
                          </el-form-item>
                          <el-form-item label="项目起日">
                            <span>{{ props.row.projectStartTime }}</span>
                          </el-form-item>
                          <el-form-item label="项目止日">
                            <span>{{ props.row.projectEndTime }}</span>
                          </el-form-item>
                          <el-form-item label="是否已签合同">
                            <span>{{ props.row.isSign }}</span>
                          </el-form-item>
                          <el-form-item label="合同总额（元）">
                            <span>{{ props.row.contractAmount }}</span>
                          </el-form-item>
                          <el-form-item label="本月收入（元）">
                            <span>{{ props.row.incomeCurrentMonth }}</span>
                          </el-form-item>
                          <el-form-item label="本次收入凭证类型">
                            <span>{{ props.row.proofType }}</span>
                          </el-form-item>
                          <el-form-item label="结算模式">
                            <span>{{ props.row.clearingMode }}</span>
                          </el-form-item>
                          <el-form-item label="甲方负责人">
                            <span>{{ props.row.firstPartyPrincipal }}</span>
                          </el-form-item>
                          <el-form-item label="乙方负责人">
                            <span>{{ props.row.secondPartyPrincipal }}</span>
                          </el-form-item>
                          <el-form-item label="甲方确认凭证编号">
                            <span>{{ props.row.firstPartyConfirmProofNumber }}</span>
                          </el-form-item>
                          <el-form-item label="需要说明的情况">
                            <span>{{ props.row.explainInfo }}</span>
                          </el-form-item>
                          <el-form-item label="上传时间">
                            <span>{{ props.row.uploadTime }}</span>
                          </el-form-item>
                        </el-form>
                      </template>
                    </el-table-column>
                  <el-table-column
                    label="单元号"
                    prop="unitNumber">
                  </el-table-column>
                  <el-table-column
                    label="年月"
                    prop="yearAndMonth">
                  </el-table-column>
                  <el-table-column
                    label="上报人"
                    prop="reportPerson">
                  </el-table-column>
                </el-table>
                <div class="pagination"><el-pagination
                    @size-change="handleSizeChange"
                    @current-change="current_change"
                    :current-page="currentPage"
                    :page-sizes="pageSizes"
                    :page-size="pagesize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
                  </el-pagination>
                </div>
          </div>
        </el-card>
    </el-col>
    </el-row>
    </div>
</template>
<script>
import { getNowDate } from "@/api/daily/daily";
import { getUserProfile } from "@/api/system/user";
import { getIncome } from "@/api/income/income";

export default {
  name: "weekSelect",
  data() {
    return {
        user: {},
        loading:false,
        searchLoading:false,
        exportLoading:false,
        SystemDate : "",
        currentPage:1,
        dailyReportFlag:false,
        total:0,
        pagesize:5,
        pageSizes:[5,10,20,30,50],
        form:{
            yearMonth:""
        },
        Salary: [],
        ServerDate : "",
        rules: {
          yearMonth:[
              { required: true, message: '请选择起止月份', trigger: 'change' }
          ]
        }
    };
},
created(){
    this.getNow();
    this.getUser();
},
methods:{
    current_change:function(currentPage){
        this.currentPage = currentPage;
      },
        handleSizeChange(val) {
        this.pagesize = Number(`${val}`);
      },
  exportExcel(){
    if(this.Salary == null || this.Salary.length == 0 || this.Salary == []){
    this.$message({
      showClose: true,
      message: '查询数据为空，无法导出！',
      type: 'error'
              });
    }else{
      this.exportLoading = true;
        import('@/utils/Export2Excel').then(excel => {
          const tHeader = ['序号',"年月","单元号","甲方全称","乙方全称","项目名称","项目内容概要","项目起日",'项目止日',"是否已签合同","合同总额（元）","本月收入（元）","本次收入凭证类型","结算模式","甲方负责人","乙方负责人","甲方确认凭证编号","需要说明的情况","上传时间"]
          const filterVal = ['id',"yearAndMonth","unitNumber","firstParty","secondParty","projectFullName","projectContent","projectStartTime",'projectEndTime',"isSign","contractAmount","incomeCurrentMonth","proofType","clearingMode","firstPartyPrincipal","secondPartyPrincipal","firstPartyConfirmProofNumber","explainInfo","uploadTime"]
          const list = this.Salary;
          const data = this.formatJson(filterVal, list);
          console.log(data);
          excel.export_json_to_excel_sheet({
            headers: [tHeader],
            datas: [data],
            sheetnames: ['SR'],
            multiHeader: [],
            autoWidth:false,
            filename: '收入导出表_'+ this.user.deptId.slice(0,5) + "_"+this.form.yearMonth.toString().replace(",","至"),
          });
          this.exportLoading = false;
          // this.downloadLoading = false
        });
        }
  },
  formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
  },
async  getUser() {
   await getUserProfile().then(response => {
      this.user = response.data;
     // console.log(this.user)
    });
  },
  getSalaryInfo(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
        this.searchLoading = true;
        getIncome(this.user.deptId.slice(0,5),this.form.yearMonth).then(res => {
        this.Salary = res;
        this.total = res.length;
        this.searchLoading = false;
        })
        } else {
          return false;
        }
      });
  },
 async getNow() {
        var nowDate = new Date();
        this.SystemDate = this.dateFormat("YYYY-mm-dd",nowDate);
     await   getNowDate().then(response =>{
          this.ServerDate = response.data;
        })
  },
dateFormat(fmt, date) {
    let ret;
    const opt = {
        "Y+": date.getFullYear().toString(),        // 年
        "m+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "M+": date.getMinutes().toString(),         // 分
        "S+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        };
    };
    return fmt;
  }
}
}
</script>
<style>
.date{
  margin-bottom: 35px;
  margin-top: 25px;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.pagination{
  margin:20px auto;
  padding-left: 36%;
}
</style>
