<template>
    <div>
        <template v-for="moduleItem in enabledModuleGroups">
            <!-- 产销情况 -->
            <mu-paper mu-paper :z-depth="3" class="lj-home-module" v-if="moduleItem.funcid === 5232">
                <div class="lj-home-module-title">
                    <i class="iconfont" :class="moduleItem.icon"
                        style="font-size: 18px;font-weight:normal;vertical-align: -1px;"></i>
                    {{moduleItem.title}}
                </div>
                <div class="lj-home-module-content" ref="moduleDiv">
                    <mu-row style="text-align: center;padding: 10px 20px 0 20px;" align-items="center">
                        <mu-col>
                            <mu-date-input v-model="yearmonth" type="month" value-format="YYYY-MM" solo full-width>
                                <i slot="prepend" class="iconfont icon-ic_event_note"></i>
                            </mu-date-input>
                        </mu-col>
                        <mu-col span="3">
                            <mu-radio value="months" v-model="requestCycle" label="月" ></mu-radio>
                        </mu-col>
                        <mu-col span="3">
                            <mu-radio value="days" v-model="requestCycle" label="日" ></mu-radio>
                        </mu-col>
                    </mu-row>
                    <canvas id="mainChart" style="width: 100%;padding:5px;" ref="cxDom"></canvas>
                </div>
            </mu-paper>
            <!-- 订单情况 -->
            <mu-paper mu-paper :z-depth="3" class="lj-home-module" v-if="moduleItem.funcid === 5233">
                <div class="lj-home-module-title">
                    <div class="flex">
                        <div class="flex_shrink-0">
                            <i class="iconfont" :class="moduleItem.icon"
                                style="font-size: 18px;font-weight:normal;vertical-align: -1px;"></i>
                            {{moduleItem.title}}
                        </div>
                        <div class="hide-eye" @click="handleSensitiveData('ifShowSale')">
                            <i class="iconfont" :class="!ifShowSale ? 'icon-yanjing_bi' : 'icon-yanjing_kai'" style="font-size: 18px"></i>
                        </div>
                    </div>

                    <div class="tips" @click="handleSaleTips" v-if="saleTips">
                        <i class="iconfont icon-question"></i>
                        {{ saleTips }}
                    </div>
                </div>
                <div class="lj-home-module-content lj-home-module-data-margin">
                    <template v-for="dataItem in dataList">
                        <div class="row-item">
                            <div class="lj-home-module-content-label">{{dataItem.label}}</div>
                            <div class="lj-home-module-content-value">{{isSensitiveData(dataItem.value, ifShowSale)}}</div>
                        </div>
                    </template>
                </div>
            </mu-paper>
            <!-- 财务状况 -->
            <mu-paper mu-paper :z-depth="3" class="lj-home-module" v-if="moduleItem.funcid === 5234">
                <div class="lj-home-module-title">
                    <div class="flex">
                        <div class="flex_shrink-0">
                            <i class="iconfont" :class="moduleItem.icon"
                                style="font-size: 18px;font-weight:normal;vertical-align: -1px;"></i>
                            {{moduleItem.title}}
                        </div>
                        <div class="hide-eye" @click="handleSensitiveData('ifShowFinance')">
                            <i class="iconfont" :class="!ifShowFinance ? 'icon-yanjing_bi' : 'icon-yanjing_kai'" style="font-size: 18px"></i>
                        </div>
                    </div>
                </div>
                <div class="lj-home-module-content">
                    <div v-for="(homeMoneyInfo, index) in dataListCW">
                        <div>
                            <mu-row>
                                <mu-col class="lj-home-module-data-margin">
                                    <div class="lj-home-module-content-label">{{homeMoneyInfo.mainlable}}</div>
                                    <div class="lj-home-module-content-value">{{isSensitiveData(homeMoneyInfo.mainvalue, ifShowFinance)}}
                                    </div>
                                </mu-col>
                                <mu-col align-self="center">
                                    <template v-for="subItem in homeMoneyInfo.sublabelvalue">
                                        <div class="lj-home-module-content-label">
                                            {{subItem.label}}
                                            <span class="sub-value">{{isSensitiveData(subItem.value, ifShowFinance)}}</span>
                                        </div>
                                    </template>
                                </mu-col>
                            </mu-row>
                        </div>
                        <div v-if="index < dataList.length - 1" class="lj-divider"></div>
                    </div>
                </div>
            </mu-paper>
            <!-- 库存情况 -->
            <mu-paper mu-paper :z-depth="3" class="lj-home-module" v-if="moduleItem.funcid === 5235">
                <div class="lj-home-module-title">
                    <i class="iconfont" :class="moduleItem.icon"
                        style="font-size: 18px;font-weight:normal;vertical-align: -1px;"></i>
                    {{moduleItem.title}}
                </div>
                <div class="lj-home-module-content" ref="moduleKC">
                    <canvas id="mtrlwareChart" style="width: 100%;padding:5px;" ref="kcDom"></canvas>
                </div>
            </mu-paper>
        </template>
    </div>
</template>

<script>
    import F2 from '@antv/f2'
    export default {
        name: "module-chart",
        props: {
            enabledFuncids: {
                type: Array,
            }
        },
        data() {
            return {
                moduleList: [{
                        title: "产销情况",
                        funcid: 5232,
                        icon: "icon-chart-line-2",
                    },
                    {
                        title: "订单情况",
                        funcid: 5233,
                        icon: "icon-write-text",
                    },
                    {
                        title: "财务状况",
                        funcid: 5234,
                        icon: "icon-financial-management",
                    },
                    {
                        title: "库存情况",
                        funcid: 5235,
                        icon: "icon-chart-bar",
                    },
                ],
                //产销情况
                homeLineRawData: {},
                f2DataLine: [],
                chart: undefined,
                requestCycle: "months",
                //订单情况
                dataList: [],
                //财务状况
                dataListCW: [],
                //库存情况
                chartData: [],
                yearmonth: null,
                loadingNum: 0,
                hasLoading: false,
                ifShowSale: false, // 订单情况，隐藏金额
                ifShowFinance: false, // 财务状况，隐藏金额
                saleTips: "", // 订单情况，提示文本
            }
        },
        created() {
            let dt = new Date();
            this.yearmonth = dt.getFullYear() + '-' + (dt.getMonth() + 1)+ "-" + dt.getDate();
            this.yearmonth = $lj.dateformat(this.yearmonth, 'yyyy-MM');
            let homeHideSensitiveData = $lj.getStorage("homeHideSensitiveData") || {};
            this.ifShowSale = homeHideSensitiveData.hasOwnProperty('ifShowSale') ? homeHideSensitiveData.ifShowSale : false;
            this.ifShowFinance = homeHideSensitiveData.hasOwnProperty('ifShowFinance') ? homeHideSensitiveData.ifShowFinance : false;
        },
        methods: {
            handleSensitiveData(prop) {
                let homeHideSensitiveData = $lj.getStorage("homeHideSensitiveData") || {};
                homeHideSensitiveData[prop] = !this[prop];
                $lj.setStorage('homeHideSensitiveData', homeHideSensitiveData);
                this[prop] = homeHideSensitiveData[prop];
            },
            handleSaleTips() {
                let userInfo = $lj.getStorage('userInfo');
                let outrepstrTips = "";
                if (userInfo.hasOwnProperty('outrepstrTips')) {
                    outrepstrTips = userInfo.outrepstrTips;
                }
                if (outrepstrTips == "0") {
                    outrepstrTips = "数据来源：全部业务员";
                } else if (outrepstrTips != "-1") {
                    outrepstrTips = "数据来源：" + outrepstrTips;
                } else {
                    outrepstrTips = "你暂无业务员权限，请联系管理员处理";
                }
                if (outrepstrTips) {
                    $lj.toast(outrepstrTips)
                }
            },
            _fnLoading(state) {
                this.loadingNum = state ? this.loadingNum + 1 : this.loadingNum - 1; 
                console.log('~~~~~~~~~~~~~~~~~~~~~~~~~~~~this.loadingNum :>>', this.loadingNum);
                if (this.loadingNum > 0 && !this.hasLoading) {
                    this.hasLoading = true;
                    api.showProgress({
                        title: '加载中',
                        text: '请稍候...',
                        modal: false
                    });
                } else if (this.loadingNum == 0 && this.hasLoading) {
                    api.hideProgress();
                    this.hasLoading = false;
                }
            },
            refreshAll() {
                if ($lj.checkPower(5232)) {
                    this.refreshCX(); //产销情况
                }
                if ($lj.checkPower(5233)) {
                    this.refreshDD(); //订单情况
                }
                if ($lj.checkPower(5234)) {
                    this.refreshCW(); //财务状况
                }
                if ($lj.checkPower(5235)) {
                    this.refreshKC(); //库存情况
                }
            },
            refreshCX() { //产销情况
                if (!$lj.getStorage("token")) {
                    return;
                }
                this._fnLoading(true);
                let self = this;
                self.homeLineRawData = {};
                let requestBody = {
                    token: $lj.getStorage("token"),
                    form: "Line",
                    cycle: this.requestCycle,
                    yearmonth: this.yearmonth
                };
                $lj.postLJRequest("GetL1HomeInfo", requestBody, function (ret) {
                    if (ret) {
                        if (ret.HomeLine) {
                            if (ret.HomeLine.labels && ret.HomeLine.datasets) {
                                self.f2DataLine = [];
                                self.homeLineRawData = ret.HomeLine;
                                let labels = self.homeLineRawData.labels;
                                let xLength = labels.length;
                                let dataSet = self.homeLineRawData.datasets;

                                for (let line of dataSet) {
                                    for (let i = 0; i < xLength; i++) {
                                        self.f2DataLine.push({
                                            x: labels[i],
                                            y: line.data[i],
                                            type: line.label
                                        });
                                    }
                                }
                                self.updateChart();
                            }
                        }
                        self._fnLoading(false);
                    }
                }, function() {
                    self._fnLoading(false);
                }, true)
            },
            updateChart() {
                // if (this.chart) {
                //     this.chart.clear();
                // }
                if (!this.$refs.moduleDiv){
                    let self = this;
                    setTimeout(()=>{
                        self.updateChart();
                    },500);
                    return;
                }
                let width = this.$refs.moduleDiv.clientWidth;
                this.chart = new F2.Chart({
                    id: 'mainChart',
                    width: width,
                    height: width * 9 / 16,
                    pixelRatio: window.devicePixelRatio
                });
                if (this.homeLineRawData.labels[0].length > 5) {
                    this.chart.axis('x', {
                        label: {
                            rotate: -Math.PI / 2,
                            textAlign: 'end',
                            textBaseline: 'middle'
                        }
                    });
                }
                // this.chart.scale('x', {
                //     tickCount: this.homeLineRawData.labels.length > 12 ? 11 : 12
                // });
                this.chart.legend({
                    align: 'center',
                    itemWidth: null // 图例项按照实际宽度渲染
                });
                this.chart.source(this.f2DataLine);
                this.chart.line().position('x*y').color('type');
                this.chart.render();
            },
            refreshDD() { //订单情况
                if (!$lj.getStorage("token")) {
                    return;
                }
                this._fnLoading(true);
                let self = this;
                $lj.postLJRequest("GetL1HomeInfo", {
                    token: $lj.getStorage("token"),
                    form: "Task"
                }, function (ret) {
                    if (ret) {
                        if (ret.HomeTaskInfo.length > 0) {
                            self.dataList = [];
                            ret.HomeTaskInfo.forEach((taskInfo) => {
                                let dataItem = {
                                    label: taskInfo.lable,
                                    value: taskInfo.value
                                };
                                self.dataList.push(dataItem);
                            })
                        }
                        self._fnLoading(false);
                    }
                }, function() {
                    self._fnLoading(false);
                }, true)
            },
            refreshCW() { //财务状况
                if (!$lj.getStorage("token")) {
                    return;
                }
                this._fnLoading(true);
                let self = this;
                $lj.postLJRequest("GetL1HomeInfo", {
                    token: $lj.getStorage("token"),
                    form: "Money"
                }, function (ret) {
                    if (ret) {
                        if (ret.HomeMoneyInfo.length > 0) {
                            self.dataListCW = [];
                            ret.HomeMoneyInfo.forEach((moneyInfo) => {
                                let dataItem = {
                                    mainlable: moneyInfo.mainlable,
                                    mainvalue: moneyInfo.mainvalue,
                                    sublabelvalue: []
                                };
                                moneyInfo.sublabelvalue.forEach((subItem) => {
                                    dataItem.sublabelvalue.push({
                                        label: subItem.lable,
                                        value: subItem.value
                                    })
                                });
                                self.dataListCW.push(dataItem);
                            })
                        }
                        self._fnLoading(false);
                    }
                }, function() {
                    self._fnLoading(false);
                }, true)
            },
            refreshKC() { //库存情况
                if (!$lj.getStorage("token")) {
                    return;
                }
                this._fnLoading(true);
                let self = this;
                $lj.postLJRequest("GetL1HomeInfo", {
                    token: $lj.getStorage("token"),
                    form: "Mtrlware"
                }, function (ret) {
                    if (ret) {
                        if (ret.HomeMtrlwareInfo.length > 0) {
                            self.chartData = []
                            ret.HomeMtrlwareInfo.forEach((mtrlwareInfo) => {
                                mtrlwareInfo.value.forEach((mwValue, index) => {
                                    let chartItem = {
                                        label: mtrlwareInfo.lable,
                                        type: index + "",
                                        value: mwValue
                                    };
                                    self.chartData.push(chartItem);
                                })
                            });
                            self.createChart();
                        }
                        self._fnLoading(false);
                    }
                }, function() {
                    self._fnLoading(false);
                }, true)
            },
            createChart() {
                if (!this.$refs.moduleKC){
                    let self = this;
                    setTimeout(()=>{
                        self.createChart();
                    },500);
                    return;
                }
                let width = this.$refs.moduleKC.clientWidth;
                let chart1 = new F2.Chart({
                    id: "mtrlwareChart",
                    width: width,
                    height: width * 9 / 16,
                    pixelRatio: window.devicePixelRatio
                });
                chart1.source(this.chartData);
                chart1.legend(false);
                chart1.interval().position('label*value').color('type').adjust({
                    type: 'dodge',
                    marginRatio: 0.05
                });
                chart1.tooltip({
					showCrosshairs: true,
                    showTooltipMarker: true,
                    onShow: function onShow(ev) {
                        const items = ev.items;
                        items[0].name = '合计';
                        items[0].value = items[0].value + '万元';
                        if (items[1]) {
                            items[1].name = '其中积压超3个月';
                            items[1].value = items[1].value + '万元';
                        }
                    }
                });
                chart1.render();
            }
        },
        computed: {
            enabledModuleGroups() {
                if (!this.enabledFuncids || this.enabledFuncids.length === 0) {
                    return [];
                }
                let funcIdsStr = ",";
                for (let funcid of this.enabledFuncids) {
                    funcIdsStr += funcid + ",";
                }
                let result = [];
                for (let module of this.moduleList) {
                    if (funcIdsStr.indexOf("," + module.funcid + ",") >= 0) {
                        result.push(module);
                    }
                }
                
                if ($lj.getOptionValue(178) == "1") {
                    let userInfo = $lj.getStorage('userInfo');
                    let outrepstrTips = userInfo.outrepstrTips;
                    if (outrepstrTips == "0") {
                        this.saleTips = "全部业务员";
                    } else if (outrepstrTips != "-1") {
                        this.saleTips = "部分业务员";
                    } else {
                        this.saleTips = "暂无业务员权限";
                    }
                }
                return result;
            },
            isSensitiveData(value, ifShow) {
                return function (value, ifShow) {
                    value = $lj.moneyFormat(value)
                    if (ifShow) {
                        return value
                    }
                    return $lj.sensitiveData(value, 'money')
                }
            }
        },
        watch: {
            requestCycle(newVal, oldVal) {
                this.refreshCX();
            },
            yearmonth(newVal, oldVal) {
                this.refreshCX();
            }
        },
    }
</script>

<style>
    .row-item {
        float: left;
        width: 50%;
    }
    
    .sub-value {
        font-weight: bold;
        color: #000;
    }
</style>