<template>
  <div class="testdiv">
    <div class="divborder newSearchDiv" style="margin:0px;">
      <div>
        <div class="filter">
          <label >{{$t('1157')}}：</label>
          <Cascader
            :data="datalevel"
            :value="leveldata"
            trigger="click"
            @on-change="handlelevelchange"
            class="searchSelect"
            change-on-select
          ></Cascader>
        </div>
        <div class="filter">
          <label>{{$t('100391')}}：</label>
          <Select v-model="materialNameId" label-in-value clearable filterable  class="searchSelect" @on-change="initSupply()">
            <Option
              v-for="item in materialNames"
              :value="item.id"
              :key="item.id"
            >{{ item.name }}</Option>
          </Select>
        </div>
        <div class="filter">
          <label>{{$t('100390')}}：</label>
          <Select v-model="material" label-in-value clearable filterable class="searchSelect" @on-change="initSupply()">
            <Option
              v-for="item in materials"
              :value="item.id"
              :key="item.id"
            >{{ item.name+"【"+ item.pn +"】" + "【" + item.spec + "】" }}</Option>
          </Select>
        </div>
        <div class="filter">
            <label>{{$t('600011')}}：</label>
            <Select
              v-model="supplier"
              label-in-value
              clearable
              filterable
              class="searchSelect"
              @on-change="supplierChange()"
            >
              <Option
                v-for="item in supplierList"
                :value="item.id"
                :key="item.id"
              >{{ item.name }}</Option>
            </Select>
          </div>
        <!-- 次级搜索条件--隐藏 -->
        <div v-show="!morecondition">
          <div>
            <div class="filter">
              <label> {{$t('1950483')}}：</label>
              <Select v-model="type" label-in-value clearable class="searchSelect" @on-change="typechange()">
                <Option :value="1" v-text="$t('8000005')">检验结果统计</Option>
                <Option :value="2" v-text="$t('8000006')">供应商PPM</Option>
                <Option :value="3" v-text="$t('8000007')">供应商不合格Top3</Option>
              </Select>
            </div>
            <div class="filter" v-show="type === 1">
              <label>{{$t('1129')}}：</label>
              <Select v-model="x_type" label-in-value clearable class="searchSelect">
                <Option :value="0" v-text="$t('1101')">天</Option>
                <Option :value="1" v-text="$t('1136')">周</Option>
                <Option :value="2" v-text="$t('1138')">月</Option>
                <Option :value="5" v-text="$t('1140')">季度</Option>
                <Option :value="4" v-text="$t('1142')">年</Option>
              </Select>
            </div>
            <div class="filter" style="margin-right: 15px;" v-show="type === 2">
              <label>TOP：</label>
              <Select v-model="top" label-in-value  class="searchSelect" filterable allow-create @on-create="handleCreate1">
                <Option v-for="item in topList1" :value="item.value" :key="item.value">{{ item.label }}</Option>
              </Select>
            </div>
            <div class="filter">
              <label>{{$t('1046')}}：</label>
              <DatePicker
                id="日期"
                type="datetimerange"
                v-model="daterange"
                confirm
                placeholder=""
                class="searchInput MaxWidth"
                format="yyyy-MM-dd HH:mm:ss"
                @on-change="selectdate"
              ></DatePicker>
            </div>
          </div>
        </div>
      </div>
      <div class="searchBtn">
        <Button type="primary" class="twoWord" icon="ios-search" @click="search()">{{$t('1001')}}</Button>
      </div>

      <!-- 更多条件 按钮 -->
      <MoreConbtn @getCon="morecondition = !morecondition" :morecondition="morecondition"></MoreConbtn>
    </div>
    <div class="divborder newEchartStyle">
      <div v-show="show_echarts==1">
        <div class="echartsId" id="chart1">
		    </div>
        <Table class="echartsTable" :columns="columns11" :data="data_table" border height="500"></Table>
      </div>
      <div v-show="show_echarts==2">
        <div class="echartsId" id="chart2"></div>
        <Table class="echartsTable" :columns="columns12" :data="data_table2" border height="500"></Table>
      </div>
      <div v-show="show_echarts==3">
        <div id="echart4" class="echarts_block"></div>
        <div id="echart5" class="echarts_block"></div>
        <div id="echart6" class="echarts_block"></div>
        <div id="echart7" class="echarts_block"></div>
      </div>

    </div>
  </div>
</template>

<script>
import axios from '@/libs/api.request'
import echarts from 'echarts'
import moment from 'moment'
import { setTimeout } from 'timers'
export default {
    data () {
        return {
            headers: {
                token: localStorage.getItem('token'),
                timestamp: localStorage.getItem('timestamp'),
                nonce: localStorage.getItem('nonce'),
                sign: localStorage.getItem('sign')
            },
            show_echarts: 0, // 变化echarts显示
            morecondition: false, // 条件
            products: [],
            dtStart: '',
            dtEnd: '',
            daterange: '',
            host: axios.publicPath,
            sectionList: [],
            supplierList: [],
            materials: [],
            leveldata: [], // 位置data
            datalevel: [], // 位置value
            sectionid: [], // 选中的value
            data_table: [], // 不良数统计table
            chartType: [],
            section: 0,
            supplier: 0,
            material: 0,
            product: 0,
            top: 0,
            type: 0,
            x_type: 0,
            columns11: [// 不良数统计表头
                {
                    title: 'MSBU incoming status',
                    align: 'center',
                    children: [
                        {
                            title: 'Month',
                            key: 'Month',
                            align: 'center'
                        },
                        {
                            title: 'Incoming batch',
                            key: 'Incoming',
                            align: 'center'
                        },
                        {
                            title: 'Defect batch',
                            key: 'Defect_batch',
                            align: 'center'
                        },
                        {
                            title: 'Defect rate',
                            key: 'Defect_rate',
                            align: 'center',
                            className: 'demo-table-info-column'
                        }
                    ]
                }
            ],
            data_table2: [],
            columns12: [
                {
                    title: this.$t(1008),
                    type: 'index',
                    width: 60,
                    align: 'center'
                },
                {
                    title: this.$t(600011),
                    key: 'month',
                    align: 'center'
                },
                {
                    title: 'PPM',
                    key: 'defect_rate',
                    align: 'center'
                }
            ],
            topList1: [
                {
                    value: '5',
                    label: '5'
                },
                {
                    value: '10',
                    label: '10'
                },
                {
                    value: '15',
                    label: '15'
                },
                {
                    value: '20',
                    label: '20'
                },
                {
                    value: '30',
                    label: '30'
                }
            ],
            materialNameId: 0,
            materialNames: []
        }
    },
    created () {
        var nowtime = Date.parse(new Date()) / 1000
        var oldtime = nowtime - 86400 * 7
        this.daterange = [
            moment(new Date().getTime() - 3600 * 1000 * 24 * 7).format('YYYY-MM-DD ') + '00:00:00',
            moment(new Date().getTime()).format('YYYY-MM-DD ') + '23:59:59'
        ]
        this.initlevel()
        this.initSupply()
        this.supplierChange()
    },
    methods: {
        supplierChange (sectionid) {
            axios.request({
                url: '/qms/IncomingMaterial/GetCheckMaterials?supplierid=' + this.supplier + '&sectionid=' + sectionid + '&materialNameId=' + this.materialNameId,
                method: 'get'
            }).then(res => {
                this.materials = res.data.data
            })
            axios.request({
                url: '/qms/IncomingMaterial/GetCheckMaterials?supplierid=' + this.supplier + '&sectionid=' + sectionid + '&distinct=1',
                method: 'get'
            }).then(res => {
                this.materialNames = res.data.data
            })
        },
        handleCreate1 (val) {
            this.topList1.push({
                value: val,
                label: val
            })
        },
        initlevel () {
            axios
                .request({
                    url: '/qms/InspectStandardMaterial/GetSectionTree',
                    method: 'get'
                })
                .then(res => {
                    const arr = []
                    this.datalevel = res.data.data
                    // arr.push(res.data.data[0].value)
                    this.leveldata = arr
                })
        },
        handlelevelchange (value) { // 位置级联选择变化函数
            this.leveldata = value
            var sectionid = value[value.length - 1]
            this.supplierChange(sectionid) // 物料变化
        },
        initSupply () {
            this.axios.request({
                url: '/qms/IncomingMaterial/GetCheckSuppliers?materialid=' + this.material + '&materialNameId=' + this.materialNameId,
                method: 'get'
            })
                .then(res => {
                    this.supplierList = res.data.data
                })
        },
        typechange () { // 图形类别变化时---->横坐标变化
            if (this.type === 1) {
                this.x_type = 0
            } else {
                this.x_type = ''
            }
        },
        search () {
            if (this.daterange.length < 1 || !this.daterange) {
                this.$Message.error(this.$t('1143'))
                return false
            }
            if (this.type != 1) {
                this.x_type = 0
            }
            if (!this.type || this.type == 0) {
                this.$Message.error(this.$t('8000009'))
                return false
            }
            this.dtStart = moment(this.daterange[0]).format('YYYY-MM-DD HH:mm:ss')
            this.dtEnd = moment(this.daterange[1]).format('YYYY-MM-DD HH:mm:ss')
            var data = {
                section: this.leveldata[this.leveldata.length - 1],
                start: this.dtStart,
                end: this.dtEnd,
                type: this.type ? this.type : 0,
                x_type: this.type === 1 ? (this.x_type ? this.x_type : 0) : 0,
                // product:this.product?this.product:0,
                material: this.material ? this.material : 0,
                supplier: this.supplier ? this.supplier : 0,
                top: this.type === 2 ? (this.top ? this.top : 0) : 0,
                materialNameId: this.materialNameId
            }
            this.axios.request({
                url: '/qms/IncomingMaterial/BadIncomingData',
                data,
                method: 'post'
            })
                .then(res => {
                    if (res.data.ret === 1) {
                        this.show_echarts = this.type
                        var data = res.data.data
                        setTimeout(() => {
                            if (this.type === 1) {
                                var x1 = data.x1
                                var y1 = data.y1
                                // var x2 = data.x2;
                                var y2 = data.y2
                                var y3 = data.y3
                                this.echarts1(x1, y1, y2, y3)
                                this.mockTableData1(res.data.data.data)// 不良率统计列表
                            } else if (this.type === 2) {
                                this.echarts2(res.data.data.x1, res.data.data.y3, res.data.data.y4)
                                this.data_table2 = res.data.data.data
                            } else {
                                for (var i = 0; i < res.data.data.length; i++) {
                                    this.echarts3(res.data.data[i].x1, res.data.data[i].y1, i, res.data.data[i].name)
                                }
                            }
                        }, 300)
                    }
                })
        },
        mockTableData1 (tablelist) {
            let data = []
            tablelist.forEach(item => {
                data.push({
                    Month: item.month,
                    Incoming: item.incoming_batch,
                    Defect_batch: item.defect_batch,
                    Defect_rate: item.defect_rate + '%'
                })
            })
            this.data_table = data
        },
        echarts1 (data_x, y1, y2, y3) {
            var myChart = echarts.init(document.getElementById('chart1'))
            var option = {
                title: {
                    text: this.$t(8000005) + '-' + this.$t(1950514),
                    y: 'top',
                    x: 'center',
                    textStyle: {
                        fontSize: 18
                    },
                    subtextStyle: {
                        fontSize: 14
                    }

                },
                tooltip: {},
                legend: {
                    data: ['Incoming batch', 'defect batch', 'Defect Rate'],
                    right: '20%',
                    bottom: '90%'
                },
                xAxis: {
                    // name:'Month',
                    data: data_x,
                    axisLabel: {
                        interval: 0, // 代表显示所有x轴标签显示
                        rotate: 38
                    }
                },
                yAxis: [
                    {
                        name: 'Batch qty',
                        type: 'value',
                        // min: 0,
                        // max: 9,
                        interval: 500,
                        show: true
                    },
                    {
                        name: 'Defect rate',
                        type: 'value',
                        // min: 0,
                        // max: 100,
                        interval: 20,
                        axisLabel: {
                            formatter: '{value} %'
                        }
                    }
                ],
                series: [
                    {
                        name: 'Incoming batch',
                        type: 'bar',
                        barMaxWidth: 70,
                        barWidth: 30,
                        data: y1, // 以通道工位报废金额排序top
                        itemStyle: {
                            normal: {
                                color: '#0F58D6'
                            }
                        },
                        label: {
                            show: true,
                            color: '#ffffff'
                        }

                    },
                    {
                        name: 'defect batch',
                        type: 'bar',
                        barWidth: 30,
                        barMaxWidth: 70,
                        data: y2, // 以通道工位报废金额排序top
                        itemStyle: {
                            normal: {
                                color: '#ED7D31'
                            }
                        },
                        label: {
                            show: true,
                            color: '#ffffff'
                        }
                    },
                    {
                        name: 'Defect Rate',
                        type: 'line',
                        yAxisIndex: 1,
                        data: y3, // 以通道工位报废金额排序top报废率
                        symbolSize: 5,
                        itemStyle: {
                            normal: {
                                label: {
                                    show: true,
                                    formatter: '{c}%',
                                    color: '#333'
                                },
                                color: 'red'
                            }
                        }
                    }
                ]
            }

            myChart.setOption(option)
            window.onresize = function () {
                myChart.resize()
            }
        },
        echarts2 (x, y, y1) { // 供应商PPM
            var myChart = echarts.init(document.getElementById('chart2'))
            var option = {
                title: {
                    text: this.$t(8000006),
                    y: 'top',
                    x: 'center',
                    textStyle: {
                        fontSize: 18
                    },
                    subtextStyle: {
                        fontSize: 14
                    }
                },
                grid: {
                    bottom: '20%'
                },
                xAxis: {
                    type: 'category',
                    data: x,
                    axisLabel: {
                        interval: 0,
                        rotate: 15
                    }
                },
                yAxis: [{
                    name: 'PPM',
                    type: 'value'
                },
                {
                    name: 'PPM' + this.$t(950016),
                    type: 'value',
                    max: 100,
                    axisLabel: {
                        formatter: '{value} %',
                        show: true
                    },
                    axisTick: {
                        show: false
                    },
                    splitLine: {
                        show: false
                    }
                }
                ],
                series: [{
                    data: y,
                    barMaxWidth: 70,
                    type: 'bar'
                },
                {
                    name: 'PPM' + this.$t(950016) + '%',
                    type: 'line',
                    xAxisIndex: 0,
                    yAxisIndex: 1,
                    smooth: true,
                    clipOverflow: false,
                    symbolSize: 9,
                    itemStyle: {
                        normal: {
                            // color:,
                            // borderColor:,
                            label: {
                                formatter: '{c} %',
                                position: '' | '',
                                show: true
                            },
                            borderWidth: 3
                        }
                    },
                    lineStyle: {
                        normal: {
                            // color:,
                            width: 4
                        }
                    },
                    data: y1
                }
                ],
                tooltip: {
                    trigger: 'axis',
                    axisPointer: { // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                    }
                }
            }
            myChart.setOption(option)
            window.onresize = function () {
                myChart.resize()
            }
        },
        echarts3 (x, y, index, name) {
            var echarts_id = 'echart' + (4 + index)
            var myChart = echarts.init(document.getElementById(echarts_id))
            var option = {
                title: {
                    text: name,
                    y: 'top',
                    x: 'center',
                    textStyle: {
                        fontSize: 18
                    },
                    subtextStyle: {
                        fontSize: 14
                    }

                },
                grid: {
                    left: '10%',
                    right: '10%',
                    bottom: '10%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: x,
                    axisLabel: {
                        interval: 0,
                        rotate: 20
                    }
                },
                yAxis: {
                    name: 'PPM',
                    type: 'value',
                    minInterval: 1 // 最小间隔为1
                },
                series: [{
                    data: y,
                    barMaxWidth: 70,
                    type: 'bar',
                    itemStyle: {
                        normal: {
                            label: {
                                show: true, // 开启显示
                                position: 'top', // 在上方显示
                                textStyle: { // 数值样式
                                    color: 'black',
                                    fontSize: 16
                                }
                            }
                        }
                    }
                }],
                tooltip: {
                    trigger: 'axis',
                    axisPointer: { // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                    }
                }
            }
            myChart.setOption(option)
            window.onresize = function () {
                myChart.resize()
            }
        },
        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]
            }
        }
    },
    mounted () {
    }
}
</script>
<style lang="less" >
.demo-table-info-column{
  background-color: red!important;
  color:#ffffff;
}
.echarts_block{
  display: inline-block;
  width: 45%;
  height: 400px;
}
</style>
