<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>
          </div>
          <div class="form">
                <el-form :rules="rules" ref="form" inline :model="form" label-width="100px" style="width:100%">
                <el-form-item label="单元号：" prop="unit" style="margin-bottom:30px">
                        <el-select 
                        v-model="form.unit"
                        placeholder="请选择单元号"
                        default-first-option
                        clearable
                        filterable>
                          <el-option
                          v-for="(item,index) of units"
                            :key="index"
                            :label="item"
                            :value="item"
                          />
                        </el-select>
                </el-form-item>
                <el-form-item label="起止月份：" prop="yearMonth">
                        <el-date-picker
                          v-model="form.yearMonth"
                          type="monthrange"
                          value-format="yyyy-MM"
                          range-separator="至"
                          start-placeholder="开始月份"
                          end-placeholder="结束月份">
                        </el-date-picker>
                </el-form-item>
                <el-button type="primary" icon="el-icon-search" :loading="searchLoading" @click="getStatictics('form')">&nbsp;查询&nbsp;</el-button>
                <el-button type="primary" icon="el-icon-document" @click="exportExcel" :loading="exportLoading">&nbsp;导出&nbsp;</el-button>
              </el-form>
          </div>
          <div id="myChart"></div>
        </el-card>
    </el-col>
    </el-row>
    </div>
</template>
<script>
import { getNowDate,getProject } from "@/api/daily/daily";
import { getMonthStatics,getMonthsStatics } from "@/api/income/income";
import Cookies from "js-cookie";

export default {
  name: "weekSelect",
  data() {
    return {
        units:[],
        statics:[],
        loading:false,
        searchLoading:false,
        exportLoading:false,
        SystemDate : "",
        currentPage:1,
        dailyReportFlag:false,
        total:0,
        pagesize:5,
        pageSizes:[5,10,20,30,50],
        form:{
            yearMonth:"",
            unit:""
        },
        Salary: [],
        ServerDate : "",
        rules: {
          yearMonth:[
            { required: true, message: '请选择起止月份', trigger: 'change' }
          ],
          unit:[
            { required: true, message: '请选择单元', trigger: 'change' }
          ]
        }
    };
},
created(){
    this.getNow();
    this.getunits();
},
mounted(){
var echarts = require('echarts');
var myChart = echarts.init(document.getElementById('myChart'));
        // 基于准备好的dom，初始化echarts实例
    myChart.setOption({
        });
    myChart.showLoading();
},
methods:{
    //获取单元号
    getunits(){
        const userId = Cookies.get("username");
        getProject(userId).then(response =>{
          this.units =  response.units;
            getMonthStatics(this.units[0]).then(res => {
            this.statics = res.data;
            var tmpCost = res.Cost;
            var tmpIncome = res.Income;
            var tmpYearMonth = res.yearAndMonth;
            var tmpunit = "";
            var netProfit = res.netProfit;
            var netProfitPrecent = res.netProfitPersent+" %";
            for(let i = 0;i< this.statics.length;i++){
              // this.statics[i].netProfitPrecent = this.statics[i].netProfitPrecent + '%';
              // tmpCost.push(this.statics[i].cost);
              // tmpIncome.push(this.statics[i].income);
              // tmpYearMonth.push(this.statics[i].yearMonth.substring(0,4)+"年"+this.statics[i].yearMonth.substring(4,6)+"月");
              tmpunit = this.statics[i].unit;
              // netProfit.push(this.statics[i].netProfit);
              // netProfitPrecent.push(this.statics[i].netProfitPrecent);
            }
            var echarts = require('echarts');
            var myChart = echarts.init(document.getElementById('myChart'));
            myChart.setOption({
            title: {
                text: tmpunit+' '+'收入\\成本\\毛利（率）'
            },
            tooltip: {},
            legend: {
                data:['成本','收入']
            },
            dataZoom: [
        {   // 这个dataZoom组件，默认控制x轴。
            type: 'slider', // 这个 dataZoom 组件是 slider 型 dataZoom 组件
            start: 0,      // 左边在 10% 的位置。
            end: 100         // 右边在 60% 的位置。
        },
        {   // 这个dataZoom组件，也控制x轴。
            type: 'inside', // 这个 dataZoom 组件是 inside 型 dataZoom 组件
            start: 0,      // 左边在 10% 的位置。
            end: 100         // 右边在 60% 的位置。
        }
    ],
            xAxis: {
                data: [tmpYearMonth]
            },
            yAxis: {},
            series: [{
                name: '成本',
                type: 'bar',
                data: [tmpCost],
                itemStyle: {
                  normal:{
                    label: {
                         show: true,
                         position: 'insideTop',
                         formatter: tmpYearMonth+ '成本 \n' + tmpCost + ' 元'+'\n\n\n'+tmpYearMonth+ '毛利 \n' + netProfit + ' 元'
                     }
                }
                }
            },
            {
                name: '收入',
                type: 'bar',
                data: [tmpIncome],
                itemStyle: {
                  normal:{
                    label: {
                         show: true,
                         position: 'insideTop',
                         formatter: tmpYearMonth+ '收入 \n' + tmpIncome + ' 元'+'\n\n\n' + tmpYearMonth + '毛利率 \n' + netProfitPrecent,
                     }
                }
                }
        }
        ],
        color:['#2f4554','#c23531']
        })
        myChart.hideLoading();
        myChart.resize();
            })
        })
    },
    current_change:function(currentPage){
        this.currentPage = currentPage;
      },
        handleSizeChange(val) {
        this.pagesize = Number(`${val}`);
      },
  exportExcel(){
    if(this.statics == null || this.statics.length == 0 || this.statics == []){
    this.$message({
      showClose: true,
      message: '查询数据为空，无法导出！',
      type: 'error'
              });
    }else{
      this.exportLoading = true;
        import('@/utils/Export2Excel').then(excel => {
          const tHeader = ["单元号","年月","成本","收入","毛利","毛利率"]
          const filterVal = ['unit',"yearMonth","cost","income","netProfit","netProfitPrecent"]
          const list = this.statics;
          const data = this.formatJson(filterVal, list);
          excel.export_json_to_excel_sheet({
            headers: [tHeader],
            datas: [data],
            sheetnames: ['收入成本'],
            multiHeader: [],
            autoWidth:false,
            filename: '收入成本毛利表',
          });
          this.exportLoading = false;
          // this.downloadLoading = false
        });
        }
  },
  formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
  },
  getNow() {
        var nowDate = new Date();
        this.SystemDate = this.dateFormat("YYYY-mm-dd",nowDate);
        getNowDate().then(response =>{
          this.ServerDate = response.data;
        })
  },
  getStatictics(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var tmpYearMonth = this.form.yearMonth.toString().replace(",","至");
          getMonthsStatics(this.form.unit,this.form.yearMonth).then(res => {
            this.statics = res.data;
            var tmpCost = res.Cost;
            var tmpIncome = res.Income;
            var tmpunit = "";
            var netProfit = res.netProfit;
            var netProfitPrecent = res.netProfitPersent+" %";
            for(let i = 0;i< this.statics.length;i++){
              tmpunit = this.statics[i].unit;
            }
            var echarts = require('echarts');
            var myChart = echarts.init(document.getElementById('myChart'));
            myChart.setOption({
            title: {
                text: tmpunit+' '+'收入\\成本\\毛利（率）'
            },
            tooltip: {},
            legend: {
                data:['成本','收入']
            },
            dataZoom: [
        {   // 这个dataZoom组件，默认控制x轴。
            type: 'slider', // 这个 dataZoom 组件是 slider 型 dataZoom 组件
            start: 0,      // 左边在 10% 的位置。
            end: 100         // 右边在 60% 的位置。
        },
        {   // 这个dataZoom组件，也控制x轴。
            type: 'inside', // 这个 dataZoom 组件是 inside 型 dataZoom 组件
            start: 0,      // 左边在 10% 的位置。
            end: 100         // 右边在 60% 的位置。
        }
    ],
            xAxis: {
                data: [tmpYearMonth]
            },
            yAxis: {},
            series: [{
                name: '成本',
                type: 'bar',
                data: [tmpCost],
                itemStyle: {
                  normal:{
                    label: {
                         show: true,
                         position: 'insideTop',
                         formatter: tmpYearMonth+ '成本 \n' + tmpCost + ' 元'+'\n\n\n'+tmpYearMonth+ '毛利 \n' + netProfit + ' 元'
                     }
                }
                }
            },
            {
                name: '收入',
                type: 'bar',
                data: [tmpIncome],
                itemStyle: {
                  normal:{
                    label: {
                         show: true,
                         position: 'insideTop',
                         formatter: tmpYearMonth+ '收入 \n' + tmpIncome + ' 元'+'\n\n\n' + tmpYearMonth + '毛利率 \n' + netProfitPrecent
                     }
                }
                }
        }
        ],
        color:['#2f4554','#c23531']
        })
        myChart.hideLoading();
        myChart.resize();
            })
        }else{
            return false;
        }
  })
  },
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%;
}
#myChart {
    height: 500px;
    width: 100%;
    margin: 20px auto;
}
</style>