<template>
    <basic-container>
        <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
            <el-tab-pane label="明细" name="first">
                <avue-crud :option="option" :table-loading="loading" :data="data" :page.sync="page" :search.sync="query"
                    v-model="form" ref="crud" id="out-table" :header-cell-class-name="headerClassName" @row-del="rowDel"
                    @search-change="searchChange" @search-reset="searchReset" @selection-change="selectionChange"
                    @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange"
                    @resetColumn="resetColumnTwo('crud', 'option', 'optionBack', 408)"
                    @saveColumn="saveColumnTwo('crud', 'option', 'optionBack', 408)" @on-load="onLoad"
                    @search-criteria-switch="searchCriteriaSwitch">
                    <template slot="menuLeft">
                        <el-button type="success" size="small" plain @click="outExport">导出</el-button>
                    </template>
                    <template slot="header">
                        <avue-crud :data="commodityData" :table-loading="itemLoading" :option="itemOption"></avue-crud>
                    </template>
                    <template slot="corpName" slot-scope="{row}">
                        <span
                            style="color: #1e9fff;cursor: pointer;width: 100%;overflow:hidden;white-space: nowrap;text-overflow: ellipsis;"
                            @click.stop="rowCell(row)">
                            {{ row.corpName }}
                        </span>
                    </template>
                </avue-crud>
                <el-dialog title="销售订单" :visible.sync="dialogVisible" width="70%" :close-on-click-modal="false"
                    v-dialog-drag append-to-body :before-close="saleClosed">
                    <span>
                        <avue-crud :data="saleData" :table-loading="saleLoading" :page.sync="salePage" :option="saleOption"
                            @current-change="saleCurrentChange" @size-change="saleSizeChange"
                            @on-load="saleOnLoad"></avue-crud>
                    </span>
                </el-dialog>
            </el-tab-pane>
            <el-tab-pane label="图表" name="second">
                <div v-loading="loading" ref="echartsContainer" style="width: 90vw; height: 56vh;margin-top: 10px;"></div>
            </el-tab-pane>
        </el-tabs>
    </basic-container>
</template>
  
<script>
import { getList, corpBuySingularSum, corpBuySingularStatistics } from "@/api/tirePartsMall/salesManagement/customAnalysis";
import { getList as getSaleList } from "@/api/tirePartsMall/salesManagement/saleOrder";
import { getToken } from "@/util/auth";
import * as echarts from 'echarts';
export default {
    data() {
        return {
            saleLoading: false,
            dialogVisible: false,
            saleForm: {},
            activeName: 'first',
            form: {},
            search: {
                chart: 1,
                type: 1,
            },
            query: {
                chart: 1,
                type: 1,
            },
            loading: false,
            itemLoading: false,
            page: {
                pageSize: 20,
                currentPage: 1,
                total: 0
            },
            saleData: [],
            salePage: {
                pageSize: 20,
                currentPage: 1,
                total: 0
            },
            selectionList: [],
            option: {},
            saleOption: {
                height: '360px',
                calcHeight: 30,
                border: true,
                index: true,
                addBtn: false,
                menu: false,
                header: false,
                column: [
                    {
                        label: "客户名称",
                        prop: "customerName",
                        overHidden: true,
                    },
                    {
                        label: "销售单号",
                        prop: "ordNo",
                        overHidden: true,
                    },
                    {
                        label: "来源单号",
                        prop: "srcOrdNo",
                        overHidden: true,
                    },
                    {
                        label: "业务日期",
                        prop: "businesDate",
                        overHidden: true,
                    },
                    {
                        label: "业务来源",
                        prop: "businessSource",
                        overHidden: true,
                    },
                    {
                        label: "数量",
                        prop: "goodsTotalNum",
                        overHidden: true,
                    },
                    {
                        label: "业务员",
                        prop: "salerName",
                        overHidden: true,
                    },
                    {
                        label: "仓库",
                        prop: "storageName",
                        overHidden: true,
                    }
                ]
            },
            optionBack: {
                height: 'auto',
                calcHeight: 30,
                searchShow: true,
                searchMenuSpan: 6,
                border: true,
                index: true,
                addBtn: false,
                menu: false,
                searchIcon: true,
                searchIndex: 3,
                column: [
                    {
                        label: "客户名称",
                        prop: "corpName",
                        type: 'select',
                        search: true,
                        filterable: true,
                        remote: true,
                        overHidden: true,
                        props: {
                            label: 'cname',
                            value: 'cname'
                        },
                        dicUrl: '/api/blade-sales-part/corpsDesc/listAll?cname={{key}}&corpType=KH&enableOrNot=1',
                    },
                    {
                        label: "单量",
                        prop: "num",
                        overHidden: true,
                    },
                    {
                        label: "条数",
                        prop: "number",
                        overHidden: true,
                    },
                    {
                        label: "最后一次购买日期",
                        prop: "date",
                        overHidden: true,
                    },
                    {
                        label: "业务日期",
                        prop: "date",
                        search: true,
                        hide: true,
                        showColumn: false,
                        overHidden: true,
                        searchProp: "dateList",
                        type: "date",
                        unlinkPanels: true,
                        searchRange: true,
                        format: "yyyy-MM-dd",
                        valueFormat: "yyyy-MM-dd HH:mm:ss",
                        searchDefaultTime: ["00:00:00", "23:59:59"],
                    },
                    {
                        label: "仓库",
                        prop: "deliveryWarehouseName",
                        overHidden: true,
                    },
                    {
                        label: '业务员',
                        prop: "salesmanName",
                        search: true,
                        type: "select",
                        props: {
                            label: "name",
                            value: "name"
                        },
                        dicUrl: "/api/blade-user/salerList",
                        filterable: true,
                    },
                    {
                        label: "购买途径",
                        prop: "purchaseMethod",
                        overHidden: true,
                    }
                ]
            },
            data: [],
            commodityData: [],
            itemOption: {
                border: true,
                align: 'center',
                header: false,
                menu: false,
                height: '90',
                column: [
                    {
                        label: "单量",
                        prop: "num",
                        overHidden: true,
                    },
                    {
                        label: "条数",
                        prop: "number",
                        overHidden: true,
                    }
                ]
            },
            chartOption: {
                height: '130px',
                calcHeight: 30,
                searchShow: true,
                searchMenuSpan: 12,
                border: true,
                addBtn: false,
                menu: false,
                header: false,
                searchLabelWidth: "80",
                align: 'center',
                column: [
                    {
                        label: "业务来源",
                        prop: "srcType",
                        search: true,
                        type: 'select',
                        filterable: true,
                        dicUrl: '/api/blade-system/dict-biz/dictionary?code=src_type_los',
                        hide: true,
                        showColumn: false,
                        overHidden: true,
                        disabled: true,
                        props: {
                            label: "dictValue",
                            value: "dictKey"
                        },
                    },
                    {
                        label: "委托人",
                        prop: "corpCnName",
                        type: 'select',
                        search: true,
                        filterable: true,
                        hide: true,
                        showColumn: false,
                        remote: true,
                        dicUrl: "/api/blade-los/bcorps/listByType?cnName={{key}}",
                        props: {
                            label: 'cnName',
                            value: 'cnName',
                            res: 'data.records'
                        },
                        width: '100',
                        overHidden: true,
                    },
                    {
                        label: "业务员",
                        prop: "srcCnName",
                        search: true,
                        width: '100',
                        overHidden: true,
                        filterable: true,
                        hide: true,
                        showColumn: false,
                        remote: true,
                        type: "select",
                        dicUrl: "/api/blade-user/page?size=20&current=1&account={{key}}",
                        props: {
                            label: "account",
                            value: "account",
                            res: 'data.records'
                        }
                    },
                    {
                        label: "场站",
                        prop: "cyCnName",
                        search: true,
                        width: '100',
                        overHidden: true,
                        filterable: true,
                        hide: true,
                        showColumn: false,
                        remote: true,
                        type: "select",
                        dicUrl: "/api/blade-los/bcorps/listByType?status=0&current=1&size=10&corpTypeName=场站&cnName={{key}}",
                        props: {
                            label: "cnName",
                            value: "cnName",
                            res: 'data.records'
                        }
                    },
                    {
                        label: "船公司",
                        prop: "carrierCnName",
                        search: true,
                        width: '100',
                        overHidden: true,
                        filterable: true,
                        hide: true,
                        showColumn: false,
                        remote: true,
                        type: "select",
                        dicUrl: "/api/blade-los/bcorps/listByType?status=0&corpTypeName=船公司&current=1&size=10&cnName={{key}}",
                        props: {
                            label: "cnName",
                            value: "cnName",
                            res: 'data.records'
                        }
                    },
                    {
                        label: "开船日期",
                        prop: "date",
                        search: true,
                        hide: true,
                        showColumn: false,
                        overHidden: true,
                        searchProp: "dateList",
                        type: "date",
                        unlinkPanels: true,
                        searchRange: true,
                        format: "yyyy-MM-dd",
                        valueFormat: "yyyy-MM-dd HH:mm:ss",
                        searchDefaultTime: ["00:00:00", "23:59:59"],
                    },
                    {
                        label: "航线",
                        prop: "lineCnName",
                        search: true,
                        hide: true,
                        showColumn: false,
                        overHidden: true,
                        filterable: true,
                        remote: true,
                        type: "select",
                        dicUrl: "api/blade-los/blines/list?status=0&current=1&size=10&cnName={{key}}",
                        props: {
                            label: "cnName",
                            value: "cnName",
                            res: 'data.records'
                        }
                    },
                    {
                        label: "业务类型",
                        prop: "businessType",
                        search: true,
                        hide: true,
                        showColumn: false,
                        overHidden: true,
                        filterable: true,
                        type: 'select',
                        dicUrl: '/api/blade-system/dict-biz/dictionary?code=decisionAnalysis_business_type',
                        props: {
                            label: "dictValue",
                            value: "dictKey"
                        },
                    },
                    {
                        label: "选择图表",
                        prop: "chart",
                        search: true,
                        hide: true,
                        showColumn: false,
                    },
                    {
                        label: "类型",
                        prop: "type",
                        search: true,
                        hide: true,
                        showColumn: false,
                    }],
            },
            chartDic: [{
                label: '箱量图',
                value: 1
            }, {
                label: '利润图',
                value: 2
            }, {
                label: '利润率图',
                value: 3
            }],
            typeDic: [{
                label: '船公司',
                value: 1
            }, {
                label: '客户',
                value: 2
            }, {
                label: '业务员',
                value: 3
            }],
            chartList: [],
            chartData: []
        };
    },
    async created() {
        this.option = await this.getColumnData(this.getColumnName(408), this.optionBack)
        this.loading = true

    },
    methods: {
        saleClosed(done) {
            this.saleData = []
            this.salePage.currentPage = 1
            this.salePage.pageSize = 20
            this.salePage.total = 0
            this.saleForm = {}
            done()
        },
        getChartData() {
            this.loading = true
            corpBuySingularStatistics(this.search).then(res => {
                this.getChart(res.data.data)
            }).finally(() => {
                this.loading = false;
            })
        },
        saleCurrentChange(currentPage) {
            this.salePage.currentPage = currentPage;
        },
        saleSizeChange(pageSize) {
            this.salePage.pageSize = pageSize;
        },
        rowCell(row) {
            this.dialogVisible = true
            this.saleForm = {
                customerName: row.corpName,
                notComplete: 1,
            }
            this.saleOnLoad(this.salePage)
        },
        saleOnLoad(page, params = {}) {
            params = {
                current: page.currentPage,
                size: page.pageSize,
                bsType: "XS",
                ...Object.assign(params, this.saleForm)
            }
            this.saleLoading = true
            getSaleList(params).then(res => {
                this.salePage.total = res.data.data.total;
                this.saleData = res.data.data.records
            }).finally(() => {
                this.saleLoading = false;
            })
        },
        handleClick() {
            if (this.activeName == 'first') {
                this.query = this.search
                this.onLoad(this.page, this.query)
            } else {
                this.getChartData()
            }
        },
        searchReset() {
            this.query = {
                chart: 1,
                type: 1,
            };
            this.onLoad(this.page);
        },
        searchCriteriaSwitch(type) {
            if (type) {
                this.option.height = this.option.height - 73;
            } else {
                this.option.height = this.option.height + 73;
            }
            this.$refs.crud.getTableHeight();
        },
        // 搜索点击回调
        searchChange(params, done) {
            this.page.currentPage = 1;
            if (params.dateList) {
                params = {
                    ...params,
                    dateStart: params.dateList[0],
                    dateEnd: params.dateList[1],
                }
            }
            this.query = params
            this.onLoad(this.page, params);
            done();
        },
        selectionChange(list) {
            this.selectionList = list;
        },
        currentChange(currentPage) {
            this.page.currentPage = currentPage;
        },
        sizeChange(pageSize) {
            this.page.pageSize = pageSize;
        },
        refreshChange() {
            this.onLoad(this.page, this.query);
        },
        onLoad(page, params = {}) {
            this.loading = true;
            if (params.dateList) {
                params = {
                    ...params,
                    dateStart: params.dateList[0],
                    dateEnd: params.dateList[1],
                }
            }
            getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
                this.page.total = res.data.data.total;
                this.data = res.data.data.records
                this.getStatisticsSum(Object.assign(params, this.query))
                this.$nextTick(() => {
                    this.$refs.crud.refreshTable()
                    this.$refs.crud.dicInit()
                })
            }).finally(() => {
                this.loading = false;
            })
        },
        getStatisticsSum(params) {
            this.itemLoading = true
            corpBuySingularSum(params).then(res => {
                this.commodityData = [res.data.data]
            }).finally(() => {
                this.itemLoading = false;
            })
        },
        outExport() {
            const routeData = this.$router.resolve({
                path: '/api/blade-sales-part/statistics/corpBuySingularExport',//跳转目标窗口的地址
                query: {
                    'Blade-Auth': getToken(),
                    ...this.query
                }
            })
            window.open(routeData.href.slice(1, routeData.href.length));
        },
        getChart(chartData) {
            let texts = ''
            let typeName = ''
            let seriesData = []
            let myChart = echarts.init(this.$refs.echartsContainer);
            // 指定图表的配置项和数据
            let option = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross',
                        crossStyle: {
                            color: '#999'
                        }
                    }
                },
                toolbox: {},
                legend: {
                    data: ['客户数量']
                },
                xAxis: [
                    {
                        type: 'category',
                        data: chartData.frequency,
                        axisPointer: {
                            type: 'shadow'
                        }
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        name: '客户数量',
                        min: 0,
                        interval: 50,
                        axisLabel: {
                            formatter: '{value} 人'
                        }
                    }
                ],
                series: [
                    {
                        name: '客户数量',
                        type: 'bar',
                        tooltip: {
                            valueFormatter: function (value) {
                                return value + ' 人';
                            }
                        },
                        data: chartData.number
                    },
                ]
            };
            myChart.setOption(option);
        },
        chartChange() {
            this.getChart(this.chartData)
        },
        //自定义列保存
        async saveColumnTwo(ref, option, optionBack, code) {
            /**
             * 已定义全局方法，直接使用，saveColumnData保存列数据方法,参数传值(表格名称，当前表格的option数据)
             * 已定义全局方法，直接使用，getColumnName方法用来获取枚举值，参数根据自己定义的code值获取中文名
             * 一定要执行异步操作，要等接口成功返回，才能执行下一行代码
             */
            const inSave = await this.saveColumnData(this.getColumnName(code), this[option]);
            if (inSave) {
                this.$message.success("保存成功");
                //关闭窗口
                this.$refs[ref].$refs.dialogColumn.columnBox = false;
            }
        },
        //自定义列重置
        async resetColumnTwo(ref, option, optionBack, code) {
            this[option] = this[optionBack];
            const inSave = await this.delColumnData(this.getColumnName(code), this[optionBack]);
            if (inSave) {
                this.$message.success("重置成功");
                this.$refs[ref].$refs.dialogColumn.columnBox = false;
            }
        },

        // 更改表格颜色
        headerClassName(tab) {
            //颜色间隔
            let back = ""
            if (tab.columnIndex >= 0 && tab.column.level === 1) {
                if (tab.columnIndex % 2 === 0) {
                    back = "back-one"
                } else if (tab.columnIndex % 2 === 1) {
                    back = "back-two"
                }
            }
            return back;
        },
    }
};
</script>
  
<style scoped>
::v-deep#out-table .back-one {
    background: #ecf5ff !important;
    text-align: center;
}

::v-deep#out-table .back-two {
    background: #ecf5ff !important;
    text-align: center;
}

::v-deep .el-col-md-8 {
    width: 24.33333%;
}

::v-deep.el-form-item {
    margin-bottom: 0;
}
</style>
  