<template>
    <div class="main">
      <div style="position: fixed;right: 0;top: 20%;z-index:99999999999">
        <commercial-type :have="3"/>
      </div>
        <header-top :bgUrl="bgUrl" :menu="menu" :bgColor="bgColor" :title="title" :analyseInfo="analyseInfo" :topBg="topBg" :page="page" :backType="backType"
                    :serverpartName="serviceInfo.SERVERPART_NAME" :spregionTypeName="serviceInfo.SPREGIONTYPE_NAME" :serviceInfo="serviceInfo"
                    :topLeftBg="topLeftBg" :topLeftColor="topLeftColor" :iconObj="iconObj" :haveIconObj="haveIconObj" :detailBoxBg="detailBoxBg"
                    :haveFun="haveFun"/>

        <div class="charts">
            <div class="chartsItem">
                <div style="display: flex;justify-content: space-between;align-items: center">
                    <p class="title">{{month}}月交易分析</p>
                    <div class="time">
                        <div class="select">
                            <picker mode="date" fields="month" :value="single" :end="endData"  @change="bindDateChange" >
                                <view class="time">
                                    <view class="uni-input"  style="background: transparent;padding: 0;height:100%">{{ single }}</view>
                                    <image class="icon" src="https://eshangtech.com/ShopICO/ahyd-BID/index/arrow_bottom.svg"></image>
                                </view>
                            </picker>
                        </div>
                    </div>
                </div>
                <div v-if="transactionList">
                    <transaction-analysis :data="transactionList" />
                </div>
                <no-data v-else />
            </div>
            <div class="chartsItem" style="margin-top: 32px">
                <p class="title">{{month}}月消费转化对比图</p>
                <div v-if="compareList.series[0].data.length>0">
                    <consumption-compare :data="compareList"/>
                    <analyse :analyseInfo="{analysisins_type: 1406,analysisins_format: 2000}" />
                </div>
                <no-data v-else />
            </div>

            <div class="chartsItem" style="margin-top: 32px">
                <p class="title">{{month}}月消费时段分析</p>
                <div v-if="timePeriodList.series.length>0">
                    <time-period-analysis :data="timePeriodList"/>
                    <analyse :analyseInfo="{analysisins_type: 1403,analysisins_format: 2000}" />
                </div>
                <no-data v-else />
            </div>
            <div class="chartsItem" style="margin-top: 32px">
                <p class="title">{{month}}月消费水平<text class="unit"></text></p>
                <div v-if="levelTopList.series.length">
                    <level-top :data="levelTopList"></level-top>
                    <analyse :analyseInfo="{analysisins_type: 1404,analysisins_format: 2000}" />
                </div>
                <no-data v-else />
            </div>
            <div class="chartsItem" style="margin-top: 32px">
                <p class="title">{{month}}月品牌消费水平<text class="unit"></text></p>
                <div v-if="bandLevelList.length>0">
                    <band-level :data="bandLevelList"/>
                    <analyse :analyseInfo="{analysisins_type: 1503,analysisins_format: 2000}" />
                </div>
                <no-data v-else/>
            </div>
            <div class="chartsItem" style="margin-top: 32px">
                <p class="title">{{month}}月业态交易值占比</p>
                <div v-if="businessTypeList.series[0].data.length>0">
                    <business-format :data="businessTypeList"/>
                    <analyse :analyseInfo="{analysisins_type: 1405,analysisins_format: 2000}" />
                </div>
                <no-data v-else />
            </div>
            <div class="chartsItem" style="margin-top: 32px">
                <p class="title">{{month}}月商超畅销品</p>
                <bestseller-shop :data="bestsellerList"/>
                <analyse :analyseInfo="{analysisins_type: 1407,analysisins_format: 2000}" />
            </div>
        </div>
    </div>
</template>

<script>
import request from '@/util/index.js'
import headerTop from "./components/headerTop.vue";
import transactionAnalysis from "./components/bussiness/transactionAnalysis.vue";
import TimePeriodAnalysis from "./components/bussiness/timePeriodAnalysis.vue";
import analyse from "./components/analyse.vue";
import LevelTop from "./components/bussiness/levelTop.vue";
import BusinessFormat from "./components/bussiness/businessFormat.vue";
import ConsumptionCompare from "./components/bussiness/consumptionCompare.vue";
import BestsellerShop from "./components/bussiness/bestsellerShop.vue";
import NoData from "./components/noData.vue";
import BandLevel from "./components/format/bandLevel.vue";
import commercialType from "./commercialType.vue";

export default {
    name: "businessPortrait",
    components: {
        BandLevel,
        NoData,
        BestsellerShop,
        ConsumptionCompare,
        BusinessFormat, LevelTop, analyse, TimePeriodAnalysis, headerTop,transactionAnalysis,commercialType},
    data() {
        return {
            topBg:'linear-gradient(180deg, #EDD1AF 0%, #EED7BB 100%);',//顶部组件的悬浮背景色
            labelList:['女性','高消费','喜爱奶茶','浙江','20-30岁','江苏'],//标签
            title:'交易画像',//页面标题
            bgColor:'180deg, #FFBA07 0%, #F38309 100%',
            bgUrl: 'https://eshangtech.com/ShopICO/ahyd-BID/newCommercialBI/businessPortraitBg.svg',//背景图片路径
            page:'/pages/commercialBI/businessPortrait',

            detailBoxBg:'linear-gradient(136deg, #F6F2E9 0%, #FFFFFF 100%);',
            topLeftBg:'linear-gradient(180deg, rgba(255, 186, 7, 0.2) 0%, rgba(243, 131, 9, 0.2) 100%)',// 类别背景
            topLeftColor:'#F38609',// 类别文字颜色
            iconObj:{
              car:'https://eshangtech.com/ShopICO/ahyd-BID/newCommercialBI/businessCar.svg',
              charge:'https://eshangtech.com/ShopICO/ahyd-BID/newCommercialBI/businessCharge.svg',
              bady:'https://eshangtech.com/ShopICO/ahyd-BID/newCommercialBI/businessBady.svg',
              guestRoom:'https://eshangtech.com/ShopICO/ahyd-BID/newCommercialBI/businessGuestRoom.svg'
            },
            haveIconObj:{
              have:'https://eshangtech.com/ShopICO/ahyd-BID/newCommercialBI/businessHave.svg',
              noHave:'https://eshangtech.com/ShopICO/ahyd-BID/newCommercialBI/businessNoHave.svg'
            },
            time: '',//跳转携带的时间
            menu: {},//手机配置信息
            transactionList:[],//交易分析数据
            timePeriodList:[],//消费时段分析
            levelTopList:[],//消费水平排行
            bandLevelList:[],//品牌消费水平
            businessTypeList:[],//业态适配型
            compareList:[],//消费转化对比图
            bestsellerList:[],//商超畅销品
            serviceInfo:{} ,//当前服务区信息
            backType:'',//返回的页面类型
            analyseInfo:{
              analysisins_type: 1401,
            },
            single:'',//显示时间
            endData:'', // 结束时间
            month:'',//显示月份
          haveFun:{}
        }
    },
    onLoad(option) {
        let serviceInfo = JSON.parse(option.serviceInfo)
        this.backType = option.type
        this.serviceInfo = serviceInfo
        //跳转的时候带上时间
        this.time = option.time
        this.endData = new Date()
    },
    onShow(){
        let storeTime = uni.getStorageSync('lastDay')
        if (storeTime){
            this.time = storeTime
        }
        this.single = this.$util.getThisMonthHave(this.time)
        const date = new Date(this.time)
        let month = date.getMonth() + 1
        this.month = month<10?'0' + month:month
        console.log('this.time',this.time)

        let storeServiceInfo = uni.getStorageSync('currentService')
        if (storeServiceInfo){
            this.serviceInfo = storeServiceInfo
        }
        //  获取手机参数对页面进行适配
        let systemInfo = uni.getSystemInfoSync()
        // 把获取到的手机参数保存
        uni.setStorageSync('phoneInfo', systemInfo)
        this.statusBarHeight = Number(systemInfo.statusBarHeight)
        this.menu = uni.getMenuButtonBoundingClientRect()
        if (!storeServiceInfo){
            this.nearestService()
        }
        //交易分析
        this.getTransactionList()
        //消费时段分析
        this.getTimePeriodList()
        //消费水平排行
        this.getLevelTopList()
        //品牌消费水平
        this.getBandLevelList()
        //业态交易值占比
        this.getBusinessTypeList()
        //消费转化对比图
        this.getCompareList()
        //商超畅销品
        this.getBestsellerList()
      //   服务区基本信息
      this.getServiceInfo()
    },
    onUnload() {
        this.$util.addUserBehavior()
    },
    methods:{
        onRefresh(){
            //交易分析
            this.getTransactionList()
            //消费时段分析
            this.getTimePeriodList()
            //消费水平排行
            this.getLevelTopList()
            //品牌消费水平
            this.getBandLevelList()
            //业态交易值占比
            this.getBusinessTypeList()
            //消费转化对比图
            this.getCompareList()
            //商超畅销品
            this.getBestsellerList()
            this.$forceUpdate()
        },
      //获取服务区基本信息
      async getServiceInfo(){
        let req = {
          ServerpartId:this.serviceInfo.Serverpart_ID
        }
        const total = await request.$webGet('CommercialApi/BaseInfo/GetServerpartInfo',req)
        this.haveFun = {
          car:total.Result_Data.HASPILOTLOUNGE,
          charge:total.Result_Data.HASCHARGE ,
          bady:total.Result_Data.HASMOTHER ,
          gusetHome:total.Result_Data.HASGUESTROOM
        }
      },
        bindDateChange(e){
            const date = new Date(e.detail.value)
            const nowDate = new Date()
            let m = date.getMonth() + 1
            let nowMonth = nowDate.getMonth() + 1
            if (nowMonth === m){
                let y = nowDate.getFullYear()
                let nowMonth = nowDate.getMonth() + 1
                let d = nowDate.getDate() - 1
                if (m<10){
                    m = '0' + m
                }
                if (nowMonth<10){
                    nowMonth = '0' + nowMonth
                }
                if (d<10){
                    d = '0' + d
                }
                this.time =`${y}-${nowMonth}-${d}`
            }else{
                let y = date.getFullYear()
                if (m<10){
                    m = '0' + m
                }
                let d = this.$util.getThisMonthDay(`${y}-${m}`)
                this.time = `${y}-${m}-${d}`
            }



            this.month = m
            this.single = e.detail.value
            let d = this.$util.getThisMonthDay(e.detail.value)
            this.endTime = e.detail.value + '-' + d
            this.onRefresh()
        },
        async nearestService(){
            let seat = uni.getStorageSync('seatInfo');
            let req = {
                longitude:seat.longitude,
                Province_Code:'340000',
                latitude:seat.latitude,
            }
            const data = await request.$webGet('CommercialApi/BaseInfo/GetServerpartList',req)
            let res = {
                SERVERPART_NAME:data.Result_Data.List[0].SERVERPART_NAME,//服务区
                SPREGIONTYPE_NAME:data.Result_Data.List[0].SPREGIONTYPE_NAME,//片区
                Serverpart_ID:data.Result_Data.List[0].SERVERPART_ID,
                longitude:data.Result_Data.List[0].SERVERPART_X,
                latitude:data.Result_Data.List[0].SERVERPART_Y,
            }
            uni.setStorageSync('currentService',res)
        },
        async getTransactionList(){
            const nowDate = new Date()
            const selectDate = new Date(this.time)
            let selectMonth = selectDate.getMonth() + 1
            let nowDateMonth = nowDate.getMonth() + 1
            let time
            if (selectMonth === nowDateMonth){
                let nowYear = nowDate.getFullYear()
                let m
                let nowDay = nowDate.getDate() - 1
                if (nowDateMonth<10){
                    m = '0' + nowDateMonth
                }
                if (nowDay<10){
                    nowDay = '0' + nowDay
                }
                time = `${nowYear}-${m}-${nowDay}`
            }else{
                let selectYear = selectDate.getFullYear()
                let m
                if (selectMonth<10){
                    m = '0' + selectMonth
                }
                let selectDay = this.$util.getThisMonthDay(`${selectYear}-${m}`)
                time = `${selectYear}-${m}-${selectDay}`
            }


            let req = {
                Province_Code:'340000',
                Statistics_Date:time,
                Serverpart_ID:this.serviceInfo.Serverpart_ID|| '',
                ShowConsumptionLevel:true,
                ShowConvertRate:true
            }
            let totalData = await request.$webGet('CommercialApi/Revenue/GetTransactionAnalysis',req)

            if (totalData.Result_Data){
                this.transactionList = totalData.Result_Data
            }else{
                this.transactionList = null
            }
            this.$forceUpdate()
            console.log('this.transactionList',this.transactionList)
        },
        async getTimePeriodList(){
            let req = {
                Province_Code:'340000',
                Statistics_Date:this.time,
                Serverpart_ID:this.serviceInfo.Serverpart_ID|| '',
                TimeSpan:1
            }
          let totalData = await request.$webGet('CommercialApi/Revenue/GetTransactionTimeAnalysis',req)
          let list = [] //客单占比
          let numberList = [] //数量数组
          let moneyList = [] // 金额数组
            if (totalData.Result_Data){
                totalData.Result_Data.CommonScatterList.forEach(item=>{
                    list.push(item.value)
                    numberList.push(item.data)
                    moneyList.push(item.key)
                })
                let res = {
                    categories: [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23],
                    series:[
                        {
                            name:'客单占比',
                            data: list,
                            number: numberList,
                            money : moneyList
                        }
                    ]
                }
                // let res = {
                //     categories: ["2018","2019","2020","2021","2022","2023"],
                //     series: [
                //         {
                //             name: "成交量A",
                //             data: [35,8,25,37,4,20]
                //         },
                //         {
                //             name: "成交量B",
                //             data: [70,40,65,100,44,68]
                //         },
                //         {
                //             name: "成交量C",
                //             data: [100,80,95,150,112,132]
                //         }
                //     ]
                // };
                this.timePeriodList = res
            }else{
                this.timePeriodList = []
            }

        },
        async getLevelTopList(){
            let req = {
                ProvinceCode:'340000',
                StatisticsDate:this.time,
                ServerpartId:this.serviceInfo.Serverpart_ID|| '',
                ShowWholeTrade:false
            }
            let res = {
                categories:[],
                series:[]
            }
            let totalData = await request.$webGet('CommercialApi/Revenue/GetBusinessTradeLevel',req)
            if (totalData.Result_Data){
                res.categories = totalData.Result_Data.legend
                totalData.Result_Data.ColumnList.forEach(item=>{
                    res.series.push({name:item.name,data:item.data})
                })
                // let res = {
                //     categories:["商超","餐饮","水果饮品","小吃","连锁品牌","全业态"],
                //     series: [
                //       {
                //         name: "低消费",
                //         textColor: "#FFFFFF",
                //         data: [20,27,21,24,6,28]
                //       },
                //       {
                //         name: "普通消费",
                //         textColor: "#FFFFFF",
                //         data: [20,27,21,24,6,28]
                //       },
                //       {
                //         name: "高消费",
                //         textColor: "#FFFFFF",
                //         data: [60,46,58,52,88,44]
                //       }
                //     ]
                // }
                this.levelTopList = res
            }else{
                this.levelTopList = []
            }

        },
        async getBandLevelList(){
            let req = {
                ProvinceCode:'340000',
                StatisticsDate:this.time,
                ServerpartId:this.serviceInfo.Serverpart_ID|| '',
                ShowWholeBrand:false
            }
            let res =[]
            let totalData = await request.$webGet('CommercialApi/Revenue/GetBusinessBrandLevel',req)
            if (totalData.Result_Data){
                totalData.Result_Data.legend.forEach(item=>{
                    res.push({name:item,small:0,normal:0,big:0})
                })
                res.forEach((item,index)=>{
                    totalData.Result_Data.ColumnList.forEach((subItem,subIndex)=>{
                        if (subItem.name==='低消费'){
                            item.small = subItem.data[index]
                        }else if(subItem.name==='普通消费'){
                            item.normal = subItem.data[index]
                        }else if(subItem.name==='高消费'){
                            item.big = subItem.data[index]
                        }
                    })
                })
                // let res=[{name:'五芳斋',big:'14.8',normal:'41.7',small:'43.5'},
                //     {name:'驿佰购',big:'44.1',normal:'31.7',small:'24.2'},
                //     {name:'老娘舅',big:'15.2',normal:'70.1',small:'14.5'},
                //     {name:'吉祥馄饨',big:'25.2',normal:'39.9',small:'34.7'}]
                this.bandLevelList = res
            }else{
                this.bandLevelList = []
            }

        },
        async getBusinessTypeList(){
            const req = {
                ProvinceCode:'340000',
                StatisticsDate:this.time,
                serverpartId:this.serviceInfo.Serverpart_ID|| '',
                BusinessTradeIds:-1
            }
            const data = await request.$webGet('CommercialApi/Revenue/GetBusinessTradeRevenue',req)
            let res = []
            let all = 0
            if (data.Result_Data){
                data.Result_Data.BusinessTradeRank.forEach((item,index)=>{
                    if (index<=10){
                        res.push({name:`${item.name} ${item.value}%`,value:Number(item.value),text:item.data})
                        all+=Number(item.value)
                    }else if(index===11){
                        if (all<100){
                            res.push({name:`其他${(100-all).toFixed(2)}%`,value:Number((100 - all).toFixed(2)),text:item.data})
                        }
                    }
                })
                let result= {
                    series: [
                        {
                            data:res
                        }
                    ]
                };
                this.businessTypeList = result
            }else{
                this.businessTypeList = []
            }

        },
        async getCompareList(){
            const req = {
                Province_Code:'340000',
                Statistics_Date:this.time,
                Serverpart_ID:this.serviceInfo.Serverpart_ID|| ''
            }
            const data = await request.$webGet('CommercialApi/Revenue/GetTransactionConvert',req)
            let customerOrder = []
            let customerMax = 0
            let carLit = []
            let carLitMax = 0
            if (data.Result_Data.TransactionList.data){
                data.Result_Data.TransactionList.data.forEach((item,index)=>{
                    if (index % 2 === 1 && index!==data.Result_Data.TransactionList.data.length-1){

                    }else{
                        if (customerMax<item[1]){
                            customerMax = item[1]
                        }
                        customerOrder.push(item[1])
                    }

                })
            }

            if (data.Result_Data.BayonetList.data){
                data.Result_Data.BayonetList.data.forEach((item,index)=>{
                    if (index % 2 === 1 && index!==data.Result_Data.BayonetList.data.length-1){

                    }else{
                        if (carLitMax<item[1]){
                            carLitMax = item[1]
                        }
                        carLit.push(item[1])
                    }
                })
            }else{
                carLit = []
            }


            let res = {
                categories: ["0:00","2:00","4:00","6:00","8:00","10:00","12:00","14:00","16:00","18:00","20:00","22:00","23:00"],
                series:[
                    {
                        index:0,
                        name: "客单数",
                        data: customerOrder,
                        max:customerMax
                    },
                    {
                        index:1,
                        name: "车辆数",
                        data: carLit,
                        max:carLitMax
                    }
                ]
            }
            // let res = {
            //     categories: ["0:00","4:00","8:00","12:00","16:00","20:00","24:00"],
            //     series: [
            //         {
            //             index:0,
            //             name: "客单数",
            //             data: [18,40,25,50,45,65,70]
            //         },
            //         {
            //             index:1,
            //             name: "车辆数",
            //             data: [180,150,170,140,130,250,280]
            //         }
            //     ]
            // }
            console.log('res',res)
            this.compareList = res
        },
        async getBestsellerList(){
            let req = {
                statisticsDate:this.time,
                provinceCode:'340000',
                Serverpart_ID:this.serviceInfo.Serverpart_ID || '',
                SPRegionType_ID:this.serviceInfo.SPRegionType_ID
            }
            const data = await request.$webGet('CommercialApi/Revenue/GetSalableCommodity',req)
            let dataFirst  = [{"name":"热销商品","value":data.Result_Data.SalableCommodity },
                {"name":"","value":100 - data.Result_Data.SalableCommodity}]
            let listFirst  = []
            let dataSecond = [{"name":"滞销商品","value":data.Result_Data.UnSalableCommodity},
                {"name":"","value":100 - data.Result_Data.UnSalableCommodity}]
            let listSecond = []
            data.Result_Data.SalableCommodityList.forEach(item=>{
                listFirst.push({name:item.Commodity_name ,value:item.Proportion })
            })
            data.Result_Data.UnSalableCommodityList .forEach(item=>{
                listSecond.push({name:item.Commodity_name ,value:item.Proportion })
            })


            let res = [
                {
                    series:[
                        {
                            data:dataFirst,
                            list:listFirst
                        }
                    ]
                },
                {
                    series:[
                        {
                            data:dataSecond,
                            list:listSecond
                        }
                    ]
                }
            ]
            // let res = [
            //     {
            //         series: [
            //             {
            //                 data: [{"name":"热销商品","value":39.8},
            //                     {"name":"","value":60.2}],
            //                 list:[{name:'红牛',value:29.3},
            //                     {name:'农夫山泉',value:25.6},
            //                     {name:'康师傅红烧牛肉面桶装牛肉面桶装',value:16.5},
            //                     {name:'方便面',value:15.2},
            //                     {name:'其他',value:13.4}]
            //             }
            //         ]
            //     },
            //     {
            //         series: [
            //             {
            //                 data: [{"name":"滞销商品","value":21.6},
            //                     {"name":"","value":78.4}],
            //                 list:[{name:'水杯',value:29.3},
            //                     {name:'吸油纸',value:25.6},
            //                     {name:'康师傅红烧牛肉面桶装牛肉面桶装',value:16.5},
            //                     {name:'纸巾',value:15.2},
            //                     {name:'其他',value:13.4}]
            //             }
            //         ]
            //     }
            // ]
            this.bestsellerList = res
        }
    }
}
</script>

<style scoped lang="scss">
.main {
  width: 100vw;
  min-height: 100vh;
    .charts{
        width: 100%;
        box-sizing: border-box;
        padding: 28px 16px 24px;
        background: #fff;
        .chartsItem{
            .title{
                font-size: 17px;
                font-family: PingFangSC-Semibold, PingFang SC;
                font-weight: 600;
                color: #160002;
                line-height: 24px;
                .unit{
                    font-size: 14px;
                    font-family: PingFangSC-Regular, PingFang SC;
                    font-weight: 400;
                    color: #786B6C;
                    line-height: 20px;
                    margin-left: 4px;
                }
            }
            .time{
                margin-bottom: 4px;
                .thisTime{
                    font-size: 14px;
                    font-family: PingFangSC-Semibold, PingFang SC;
                    font-weight: 500;
                    color: #160002;
                }
                .select{
                    margin-left: 8px;
                    display: inline-block;
                    .time {
                        display: flex;
                        align-items: center;
                        margin-right: 4px;
                        .day {
                            font-size: 32rpx;
                            font-family: PingFangSC-Regular, PingFang SC;
                            font-weight: 400;
                            color: #782717;
                            line-height: 44rpx;
                            margin-right: 4px;
                        }
                        .uni-input {
                            font-size: 14px;
                            font-family: PingFangSC-Regular, PingFang SC;
                            font-weight: 400;
                            color: #ae664e;
                            line-height: 36rpx;
                        }
                        .icon {
                            width: 24px;
                            height: 16px;
                        }
                    }
                }
            }
        }
    }
}
</style>
