<template>
    <widget-card :bodyStyle="bodyStyle" ref="container" class="chart-container">
        <div slot="header">区域存栏数</div>
        <div ref="chart" class="chart"></div>
    </widget-card>
</template>
<script>
    import WidgetCard from './WidgetCard'
    import {mapState} from 'vuex'
    import axios from 'axios'

    export default {
        mounted() {
            require.ensure(['@antv/g2'], require => {
                const G2 = require('@antv/g2');
                axios.get(this.$widgetBaseUrl + 'api/Values/GetCowsQYCLS', {
                    withCredentials: false
                }).then(res => {
                    if (res.data.rtnCode > 0) {
                        let data = [];
                        res.data.rtnList.forEach(i => {
                            if (!i['当前牧场']) return;
                            data.push({
                                "牧场": i['当前牧场'],
                                "牛数": i["后备牛"],
                                type: '后备牛'
                            });
                            data.push({
                                "牧场": i['当前牧场'],
                                "牛数": i["泌乳牛"],
                                type: '泌乳牛'
                            });
                            data.push({
                                "牧场": i['当前牧场'],
                                "牛数": i["干奶牛"],
                                type: '干奶牛'
                            });
                        });
                        this.chartData = data;
                        this.drawChart(G2);
                    }
                })
            });
        },
        data() {
            return {
                myChart: null,
                bodyStyle: {
                    display: 'flex',
                    alignItems: 'center'
                },
                chartData: []
            }
        },
        computed: {
            ...mapState(['farmName'])
        },
        methods: {
            drawChart(G2) {
                let chart = new G2.Chart({
                    container: this.$refs.chart,
                    forceFit: true,
                    height: this.$refs.container.$el.offsetHeight - 75,
                    padding: 'auto',
                    options: {
                        legends: {
                            position: 'bottom',
                        }
                    }
                });
                chart.source(this.chartData);
                chart.intervalStack().position('牧场*牛数').color('type');
                chart.render();
            }
        },
        components: {
            WidgetCard
        }
    }
</script>
<style lang="less" scoped>
    .chart {
        width: 100%;
    }
</style>
