<template>
  <el-dialog
    :model-value="modelValue"
    fullscreen
    :title="props.title"
    destroy-on-close
    :before-close="() => emits('update:modelValue', false )"
  >
    <el-row>
      <el-col :span="20">
        <el-row
          style="height: 20vh"
        >
          <v-chart
            class="chart1"
            autoresize
            :option="option1"
          />
        </el-row>

        <el-row
          style="height: 20vh"
        >
          <v-chart
            class="chart2"
            autoresize
            :option="option2"
          />
        </el-row>

        <el-row
          style="height: 20vh"
        >
          <v-chart
            class="chart3"
            autoresize
            :option="option3"
          />
        </el-row>

        <el-col style="height: 10vh; text-align: center; margin-top: 10px">
          <el-button
            class="btn-right"
            style="background: #5B79D7;"
			@click="prevClick"
          >
            上一班次
          </el-button>

          <span
            style="font-size: 26px;vertical-align: middle;margin: 20px"
          >当前班次:{{ currentFrequency }}</span>

          <el-button
            class="btn-right"
			@click="nextClick"
            style="background: #5B79D7;"
          >
            下一班次
          </el-button>
        </el-col>

      </el-col>

      <el-col :span="4">
        <div
          style="font-size: 22px; margin-left: 30px"
        >设备状态：</div><br>
        <el-button
          class="btn-right"
          :class="{ 'active': activeBtn === '待单'}"
          @click="handleBtnActive"
        >待单</el-button><br>
        <el-button
          class="btn-right"
          :class="{ 'active': activeBtn === '维修' }"
          @click="handleBtnActive"
        >维修</el-button><br>
        <el-button
          class="btn-right"
          :class="{ 'active': activeBtn === '保养' }"
          @click="handleBtnActive"
        >保养</el-button><br>
        <el-button
          class="btn-right"
          :class="{ 'active': activeBtn === '测试' }"
          @click="handleBtnActive"
        >测试</el-button><br>
        <el-button
          class="btn-right"
          :class="{ 'active': activeBtn === '打样' }"
          @click="handleBtnActive"
        >打样</el-button><br>
        <el-button
          class="btn-right"
          :class="{ 'active': activeBtn === '待料' }"
          @click="handleBtnActive"
        >待料</el-button><br>
        <el-button
          class="btn-right"
          :class="{ 'active': activeBtn === '装版' }"
          @click="handleBtnActive"
        >装版</el-button><br>
        <el-button
          class="btn-right"
          :class="{ 'active': activeBtn === '生产' }"
          @click="handleBtnActive"
        >生产</el-button><br>
      </el-col>
    </el-row>
  </el-dialog>

</template>
<script>
export default {
  name: 'Shebeizhuangtai',
}
// 机台数据详情
import service from '@/utils/request'
const getMachineDetail = (params) => {
  return service({
    url: '/mes_server/facility/MachineDetail',
    method: 'get',
    params
  })
}

const setMachineStatus = (data) => {
  return service({
    url:'/mes_server/reporting_work/setMachineStatus',
    method: 'post',
    data
  })
}


</script>

<script setup>
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { BarChart, LineChart, PieChart, ScatterChart } from 'echarts/charts'
import { GridComponent, LegendComponent, TitleComponent, TooltipComponent } from 'echarts/components'
import VChart, { THEME_KEY } from 'vue-echarts'
import { defineEmits, defineProps, provide, ref } from 'vue'

const props = defineProps(['modelValue', 'title','formData'])
const emits = defineEmits(['update:modelValue'])

use([
  CanvasRenderer,
  PieChart,
  BarChart,
  LineChart,
  ScatterChart,
  GridComponent,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
])
// provide(THEME_KEY, 'dark')
const currentFrequency = ref()
const timeDifference=ref([0,0,0,0,0,0,0,0])
const timeRow=ref([])
const timeData=ref([])
const activeBtn = ref(null)
const handleBtnActive = async(e) => {
  if(activeBtn.value == e.target.innerText){
	  console.log(props.formData)
  }else{
	  const response = await setMachineStatus({
		  machine:props.formData.machine.split('#')[0],
		  order:props.formData.工单编号,
		  yjno:props.formData.印件号,
		  gy_name:props.formData.工序名称.split('【')[0],
		  class:props.formData.class,
		  status:e.target.innerText,
		  production_now:props.formData.production_now,
		  production_all:props.formData.production_all
	  });
	  if(response.code === 0){
		  activeBtn.value = e.target.innerText
	  }
  }
}

const prevClick = async() => {
	if(currentFrequency.value.split(' ')[1].substring(0,2)=='08'){
		let previousDay = new Date(currentFrequency.value); // 创建一个表示当前时间的Date对象
		previousDay.setDate(previousDay.getDate() - 1); // 将日期设置为前一天
		let year = previousDay.getFullYear();
		let month = previousDay.getMonth() + 1;
		let day = previousDay.getDate();
		currentFrequency.value=`${year}-${month}-${day} 20:30:00`
		console.log(currentFrequency.value); // 输出前一天日期
	}else{
		let now = currentFrequency.value.split(' ')[0]
		currentFrequency.value=`${now} 08:30:00`
	}
	GetMachineDetail()
}

const nextClick = async() => {
	if(currentFrequency.value.split(' ')[1].substring(0,2)=='20'){
		let nextDay = new Date(currentFrequency.value); // 创建一个表示当前时间的Date对象
		nextDay.setDate(nextDay.getDate() + 1); // 将日期设置为后一天
		let year = nextDay.getFullYear();
		let month = nextDay.getMonth() + 1;
		let day = nextDay.getDate();
		currentFrequency.value=`${year}-${month}-${day} 08:30:00`
	}else{
		let now = currentFrequency.value.split(' ')[0]
		currentFrequency.value=`${now} 20:30:00`
	}
	GetMachineDetail()
}


const GetMachineDetail = async() => {
	timeDifference.value=[0,0,0,0,0,0,0,0]
	timeRow.value=[]
	timeData.value=[]
	const data = []
	for (let i = 510; i <= 1230; i++) { // 08:30 到 20:30 的分钟数范围
	  const hours = Math.floor(i / 60)
	  const minutes = i % 60
	  const time = (hours < 10 ? '0' + hours : hours) + ':' + (minutes < 10 ? '0' + minutes : minutes)
	  data.push([time, 0])
	}
	const response = await getMachineDetail({machine:props.formData.machine,start:currentFrequency.value});
	if (response.code === 0) {
		  response.data.timeDifference.map(item=>{
			  switch(item.状态) {
			  case '维修':
			  timeDifference.value[1]=item.时间?item.时间:0;
			  break;
			  case '保养':
			  timeDifference.value[2]=item.时间?item.时间:0;
			  break;
			  case '测试':
			  timeDifference.value[3]=item.时间?item.时间:0;
			  break;
			  case '打样':
			  timeDifference.value[4]=item.时间?item.时间:0;
			  break;
			  case '待料':
			  timeDifference.value[5]=item.时间?item.时间:0;
			  break;
			  case '装版':
			  timeDifference.value[6]=item.时间?item.时间:0;
			  break;
			  case '生产':
			  timeDifference.value[7]=item.时间?item.时间:0;
			  break;
			  case '':
			  timeDifference.value[0]=item.时间?item.时间:0;
			  break;
			  default:
			  }
		  })
		  response.data.row.map(item=>{
			  data.map(items=>{
				  if(item.时间.split(' ')[1]==items[0]){
					  items[1]=item.产能
				  }
				  return items
			  })
		  })
		  option1.value = {
		    xAxis: {
		      data: ['待单', '维修', '保养', '测试', '打样', '待料', '装版', '生产'],
		    },
		    yAxis: {
		      name: '状态时长（小时）',
		      nameLocation: 'end',
		      nameGap: 5,
		      nameTextStyle: {
		        align: 'left',
		        verticalAlign: 'bottom',
		      },
		    },
		    grid: {
		      left: '8%',
		      right: '2%',
		      top: '22%',
		      bottom: '15%',
		    },
		    series: {
		      type: 'bar',
		      label: {
		        show: true,
		        position: 'top',
		      },
		      data: timeDifference.value,
		    },
		    textStyle: {
		      fontWeight: 'bolder',
		      fontSize: 16,

		    },
		  }
		  option2.value={
			  xAxis: {
				type: 'category',
				axisLabel: {
				  interval: 59, // 控制显示的刻度标签间隔，每小时一个
				},
			  },
			  yAxis: {
				name: '实时产量',
				nameLocation: 'end',
				nameGap: 5,
				nameTextStyle: {
				  align: 'left',
				  verticalAlign: 'bottom',
				}
			  },
			  grid: {
				left: '8%',
				right: '2%',
				top: '22%',
				bottom: '15%',
			  },
			  tooltip: {
				trigger: 'axis'
			  },
			  series: {
				name: '速度',
				type: 'line',
				data: data,
			  },
			  textStyle: {
				fontWeight: 'bolder',
				fontSize: 16,
			  },
			}
			response.data.首件.map(item=>{
				timeData.value.push([item.split(' ')[1].substring(0,5),'首件与过程'])
			})
			response.data.自检.map(item=>{
				timeData.value.push([item.split(' ')[1].substring(0,5),'机台检验'])
			})
			response.data.IPQC.map(item=>{
				timeData.value.push([item.split(' ')[1].substring(0,5),'IPQC检验'])
			})
			option3.value = {
			  xAxis: {
			    // type: 'value',
			    data: xAxisData,
			    axisLabel: {
			      interval: 59, // 控制显示的刻度标签间隔，每小时一个
			    },
			  },
			  yAxis: {
			    name: '检验时间',
			    nameLocation: 'end',
			    nameGap: 5,
			    nameTextStyle: {
			      align: 'left',
			      verticalAlign: 'bottom'
			    },
			    axisLine: {
			      show: true,
			    },
			    data: ['IPQC检验', '机台检验', '首件与过程'],
			  },
			  tooltip: {
			    trigger: 'item'
			  },
			  grid: {
			    left: '8%',
			    right: '2%',
			    top: '22%',
			    bottom: '15%',
			  },
			  series: {
			    type: 'scatter',
			    symbol: 'arrow',
			    symbolSize: 20,
			    label: {
			      show: true,
			      position: 'right',
			      formatter: '{@value}' // 点旁边显示label，这里使用name: '横坐标'这样写也可以，鼠标移入出现提示。
			    },
			    data: timeData.value,
			  },
			  textStyle: {
			    fontWeight: 'bolder',
			    fontSize: 16,
			  },
			}
	}
}



const option1 = ref({
  xAxis: {
    data: ['待单', '维修', '保养', '测试', '打样', '待料', '装版', '生产'],
  },
  yAxis: {
    name: '状态时长（小时）',
    nameLocation: 'end',
    nameGap: 5,
    nameTextStyle: {
      align: 'left',
      verticalAlign: 'bottom',
    },
  },
  grid: {
    left: '8%',
    right: '2%',
    top: '22%',
    bottom: '15%',
  },
  series: {
    type: 'bar',
    label: {
      show: true,
      position: 'top',
    },
    data: timeDifference.value,
  },
  textStyle: {
    fontWeight: 'bolder',
    fontSize: 16,

  },
})

// 生成横坐标（每分钟一个点，显示时间格式为 "HH:mm"）
const data = []
for (let i = 510; i <= 1230; i++) { // 08:30 到 20:30 的分钟数范围
  const hours = Math.floor(i / 60)
  const minutes = i % 60
  const time = (hours < 10 ? '0' + hours : hours) + ':' + (minutes < 10 ? '0' + minutes : minutes)
  data.push([time, 0])
}
const Worklist = async () => {
	let now = new Date();
	let year = now.getFullYear();
	let month = now.getMonth() + 1;
	let day = now.getDate();
	let hour = now.getHours();
	let minute = now.getMinutes();
	let second = now.getSeconds();
	if(hour>=20){
		currentFrequency.value=`${year}-${month}-${day} 20:30:00`
	}else{
		currentFrequency.value=`${year}-${month}-${day} 08:30:00`
	}
	activeBtn.value=props.formData['status']
	GetMachineDetail()
}
Worklist()
const xAxisData = data.map(item => item?.[0])

const option2 = ref({
  xAxis: {
    type: 'category',
    axisLabel: {
      interval: 59, // 控制显示的刻度标签间隔，每小时一个
    },
  },
  yAxis: {
    name: '实时产量',
    nameLocation: 'end',
    nameGap: 5,
    nameTextStyle: {
      align: 'left',
      verticalAlign: 'bottom',
    }
  },
  grid: {
    left: '8%',
    right: '2%',
    top: '22%',
    bottom: '15%',
  },
  tooltip: {
    trigger: 'axis'
  },
  series: {
    name: '速度',
    type: 'line',
    data: data,
  },
  textStyle: {
    fontWeight: 'bolder',
    fontSize: 16,
  },
})

const option3 = ref({
  xAxis: {
    // type: 'value',
    data: xAxisData,
    axisLabel: {
      interval: 59, // 控制显示的刻度标签间隔，每小时一个
    },
  },
  yAxis: {
    name: '检验时间',
    nameLocation: 'end',
    nameGap: 5,
    nameTextStyle: {
      align: 'left',
      verticalAlign: 'bottom'
    },
    axisLine: {
      show: true,
    },
    data: ['IPQC检验', '机台检验', '首件与过程'],
  },
  tooltip: {
    trigger: 'item'
  },
  grid: {
    left: '8%',
    right: '2%',
    top: '22%',
    bottom: '15%',
  },
  series: {
    type: 'scatter',
    symbol: 'arrow',
    symbolSize: 20,
    label: {
      show: true,
      position: 'right',
      formatter: '{@value}' // 点旁边显示label，这里使用name: '横坐标'这样写也可以，鼠标移入出现提示。
    },
    data: timeData.value,
  },
  textStyle: {
    fontWeight: 'bolder',
    fontSize: 16,
  },
})

</script>

<style scoped>
.active {
  background-color: #528B34 !important;
}

.btn-right {
  width: 100px;
  height: 50px;
  margin-bottom: 5px;
  margin-left: 30px;
  color: #FFFFFF;
  background-color: #C6BEC4;
  font-size: 20px;
  font-style: italic;
}
</style>
