<template>
  <div class="testdiv">
    <div class="divborder newSearchDiv" style="margin:0px;">

        <div class="filter">
          <label>{{$t('1950491')}}：</label>
          <Cascader
            :data="datalevel"
            :value="leveldata"
            trigger="click"
            @on-change="handlelevelchange"
            change-on-select
            class="searchSelect"
          ></Cascader>
        </div>
        <div class="filter">
          <label>{{$t('100307')}}：</label>
          <Select v-model="productid" label-in-value clearable filterable class="searchSelect">
            <Option
              v-for="item in products"
              :value="item.id"
              :key="item.id"
            >{{ item.name+"【"+ item.code +"】" }}</Option>
          </Select>
        </div>
        <div class="filter">
          <label>{{$t('1046')}}：</label>
          <DatePicker
            id="日期"
            type="datetimerange"
            v-model="daterange"
            confirm
            placeholder=""
            class="searchInput middleWidth  "
            format="yyyy-MM-dd"
            @on-change="selectdate"
          ></DatePicker>
        </div>

        <div class="filter">
          <label>{{$t('99200005')}}：</label>
          <Select v-model="chartType" label-in-value clearable class="searchSelect">
            <Option :value="1">{{$t('99200006')}}</Option>
            <Option :value="2">{{$t('99200007')}}</Option>
            <Option :value="3">{{$t('99200008')}}</Option>
            <Option :value="4">{{$t('99200009')}}</Option>
            <Option :value="5">{{$t('99200010')}}</Option>
            <Option :value="6">{{$t('99200011')}}</Option>
            <Option :value="7">{{$t('99200012')}}</Option>
            <Option :value="8">{{$t('99200013')}}</Option>

          </Select>
        </div>
         <!-- 次级搜索条件--隐藏 -->
                <div v-show="!morecondition">
        <div class="filter">
          <label>{{$t('9900087')}}：</label>
          <Select v-model="xType" label-in-value clearable class="searchSelect">
            <Option :value="1">{{$t('99200014')}}</Option>
            <Option :value="2">{{$t('99200015')}}</Option>
          </Select>
        </div>
                </div>

      <div class="searchBtn">
        <Button type="primary" class="twoWord intervalRight" icon="ios-search" @click="search()">{{$t('1001')}}</Button>
        <Button type="primary" class="fourWord" icon="ios-cloud-download" @click="downexcel()">{{$t('1007')}}</Button>
      </div>
      <!-- 更多条件 按钮 -->
      <MoreConbtn @getCon="morecondition = !morecondition" :morecondition="morecondition"></MoreConbtn>
    </div>
    <div class="divborder newEchartStyle">
      <div class="echartsId" id="div_echarts">
		  </div>
      <Table
        class="echartsTable"
        @on-current-change="handleRowChange"
        highlight-row
        :data="tableData1"
        :columns="tableColumns1"
      ></Table>
    </div>
  </div>
</template>

<script>
import axios from '@/libs/api.request'
import echarts from 'echarts'
import moment from 'moment'
export default{
    data () {
        return {
            morecondition: false, // 条件
            chartType: 1, // 统计图表
            sectionid: 0,
            xType: 1, // 统计维度
            xname: '', // x轴名称
            yname: '', // y轴名称
            leveldata: [],
            datalevel: [],
            productid: 0,
            products: [],
            tableData1: [],
            daterange: [],
            tableColumns1: [
                {
                    type: 'index',
                    title: this.$t('1008'),
                    key: 'xuhao',
                    width: 70
                },
                {
                    title: '工位',
                    key: 'sectionname'
                },
                {
                    title: '金额/报废率',
                    key: 'num'
                }
            ],
            loading: false
        }
    },
    created () {

    },
    mounted () {
        var nowtime = Date.parse(new Date()) / 1000
        var oldtime = nowtime - 86400 * 7
        this.daterange = [this.datetrans(oldtime), this.datetrans(nowtime)]
        this.selectdate(this.daterange)
        this.initlevel()
        this.initproducts()
        this.search()
    },
    methods: {
        datetrans (date) {
            if (date === '' || date === undefined || date === 0 || date === null) {
                return ''
            }
            date = new Date(date * 1000)
            var Y = date.getFullYear() + '-'
            var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
            var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' '
            return Y + M + D
        },
        handlelevelchange (data) {
            this.leveldata = data
            if (data && data.length > 0) {
                this.sectionid = data[data.length - 1]
                this.initproducts()
            }
        },
        initlevel () {
            axios.request({
                url: 'config/ProjectLevelSection/GetSectionTree',
                method: 'get'
            }).then(res => {
                var arr = []
                this.datalevel = res.data.data
                arr.push(res.data.data[0].value)
                this.leveldata = arr
            })
        },
        selectdate (e) {
            this.dtStart = e[0]
            this.dtEnd = e[1]
            // let last_str = this.dtEnd.split(' ')[1]
            // if (last_str === '00:00:00') {
            //   this.dtEnd = moment(this.dtEnd).format('YYYY-MM-DD') + ' 23:59:59'
            //   this.daterange = [this.dtStart, this.dtEnd]
            // }
        },
        initproducts () {
            axios.request({
                url: '/qms/SendTestCollection/GetInspectionProducts?sectionid=' + this.sectionid + '&iscompelete=1',
                method: 'get'
            }).then(res => {
                if (res.data.ret === 1 && res.data.data.length > 0) {
                    this.products = res.data.data
                }
            })
        },
        search () {
            var params = {
                productId: this.productid,
                section: this.sectionid,
                starttime: this.dtStart,
                endtime: this.dtEnd,
                chartType: this.chartType,
                xType: this.xType
            }

            axios.request({
                url: '/qms/RepairData/GetWasteAnalysis',
                params,
                method: 'get'
            }).then(res => {
                if (res.data.ret === 1) {
                    var data = res.data.data

                    switch (this.chartType) {
                    case 1:
                        this.xname = this.$t('5000009')
                        break;
                    case 2:
                        this.xname = this.$t('1026');
                        break;
                    case 3:
                        this.xname = this.$t('99200017');
                        break;
                    case 4:
                        this.xname = this.$t('99200018');
                        break;
                    case 5:
                        this.xname = this.$t('99200019');
                        break;
                    case 6:
                        this.xname = this.$t('600532');
                        break;
                    case 7:
                        this.xname = this.$t('600532');
                        break;
                    case 8:
                        this.xname = this.$t('600532');
                        break;
                    default:
                        this.xname = '';
                        break;
                    }
                    switch (this.xType) {
                    case 1:
                        this.yname = this.$t('99200014') + ' 单位/元';
                        break;
                    case 2:
                        this.yname = this.$t('5000048');
                        break;
                    default:
                        this.title = '';
                        break;
                    }

                    var xdata = data.x // ['op10','op20','op30','op40','op50']
                    var ydata = data.y // [10,20,30,40]
                    var zdata = data.z // [10,30,60,100]
                    var tables = data.tables;
                    // 柱状图
                    if (this.chartType === 1 || this.chartType === 2) {
                        // 画图-通道 工位

                        this.getEcharts(xdata, ydata)
                    } else // 柏拉图
                    {
                        // 画图
                        this.getEchartsTwo(xdata, ydata, zdata)
                    }
                    this.tableColumns1 = [
                        {
                            type: 'index',
                            title: this.$t('1008'),
                            key: 'xuhao',
                            width: 70
                        },
                        {
                            title: this.xname,
                            key: 'Item'
                        },
                        {
                            title: this.yname,
                            key: 'Val'
                        }
                    ]
                    this.mockTableData1(tables)
                }
            })
        },
        mockTableData1 (tablelist) {
            let data = []
            tablelist.forEach(item => {
                if (item) {
                    data.push({
                        Item: item.item,
                        Val: item.val
                        // batch: item.batch_quantity,
                        // numRate: item.quantity_rate+"%",
                        // batchRate: item.batch_quantity_rate+"%"
                    })
                }
            })
            this.tableData1 = data
        },
        getEcharts (x1, y1) {
            this.initEchartsbase('div_echarts', x1, y1)
        },
        getEchartsTwo (x2, y2, z2) {
            this.initEcharts('div_echarts', x2, y2, z2)
        },
        initEchartsbase (id, x, y) {
            var myChart = echarts.init(document.getElementById(id))
            var option = {
                title: {
                    text: '',
                    subtext: '',
                    textStyle: {
                        fontSize: 18
                    },
                    subtextStyle: {
                        fontSize: 14
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross',
                        crossStyle: {
                            color: '#999'
                        }
                    }
                },
                color: ['#59A9FA'],
                legend: {
                    data: [this.yname]
                },
                xAxis: [
                    {
                        type: 'category',
                        name: '',
                        data: x,
                        axisPointer: {
                            type: 'shadow'
                        }
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        name: this.yname,
                        min: 0,
                        // max: 250,
                        // interval: 200,
                        axisLabel: {
                            formatter: '{value}'
                        }
                    }
                ],
                series: [
                    {
                        name: this.yname,
                        type: 'bar',
                        data: y,
                        barMaxWidth: 70, // 柱子最大宽度
                        itemStyle: {
                            normal: {
                                label: {
                                    show: true, // 开启显示
                                    position: 'top', // 在上方显示
                                    textStyle: { // 数值样式
                                        color: 'black'
                                        // fontSize: 12
                                    }
                                }
                            }
                        }
                    }
                ]
            };
            myChart.setOption(option)
            window.onresize = function () {
                myChart.resize()
            }
        },
        initEcharts (id, x, y, z) {
            var myChart = echarts.init(document.getElementById(id))
            var option = {
                title: {
                    text: '',
                    subtext: '',
                    textStyle: {
                        fontSize: 18
                    },
                    subtextStyle: {
                        fontSize: 14
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross',
                        crossStyle: {
                            color: '#999'
                        }
                    }
                },
                color: ['#59A9FA', 'green'],
                legend: {
                    data: [this.yname, '占比']
                },
                xAxis: [
                    {
                        type: 'category',
                        data: x,
                        axisPointer: {
                            type: 'shadow'
                        }
                    }
                ],
                yAxis: [
                    {
                        type: 'value',
                        name: this.yname,
                        min: 0,
                        // max: 250,
                        // interval: 200,
                        axisLabel: {
                            formatter: '{value}'
                        }
                    },
                    {
                        type: 'value',
                        name: '百分比',
                        min: 0,
                        max: 100,
                        interval: 20,
                        axisLabel: {
                            formatter: '{value} %'
                        }
                    }
                ],
                series: [
                    {
                        name: this.yname,
                        type: 'bar',
                        data: y,
                        barMaxWidth: 70, // 柱子最大宽度
                        itemStyle: {
                            normal: {
                                label: {
                                    show: true, // 开启显示
                                    position: 'top', // 在上方显示
                                    textStyle: { // 数值样式
                                        color: 'black'
                                        // fontSize: 12
                                    }
                                }
                            }
                        }
                    },

                    {
                        name: '占比',
                        type: 'line',
                        yAxisIndex: 1,
                        data: z,
                        smooth: true,
                        itemStyle: {
                            normal: {
                                label: {
                                    formatter: function (data) {
                                        return data.value + '%'
                                    },
                                    show: false, // 开启显示
                                    position: 'top', // 在上方显示
                                    textStyle: { // 数值样式
                                        color: 'black'
                                        // fontSize: 12
                                    }
                                }
                            }
                        }
                    }
                ]
            };
            myChart.setOption(option)
            window.onresize = function () {
                myChart.resize()
            }
        },
        downexcel () {
            var params = {
                productId: this.productid,
                section: this.sectionid,
                starttime: this.dtStart,
                endtime: this.dtEnd,
                chartType: this.chartType,
                xType: this.xType
            }
            axios.request({
                url: '/qms/RepairData/ExportEexcel',
                params,
                method: 'get'
            }).then(res => {
                if (res.data.ret === 1) {
                    window.location.href = axios.publicPath + '' + res.data.data
                } else {
                    this.$Message.error(this.$t(res.data.msg))
                }
            })
        },
        handleRowChange (currentRow, oldCurrentRow) {

        }
    }
}

</script>
<style lang="less" scoped>

</style>
