<template>
	<div>
		<el-card style="height: 867px">
			<span>工位：</span>
			<el-select v-model="opnameThis" style="width:250px" placeholder="工位号">
				<el-option
					v-for="item in opnames"
					:key="item.value"
					:label="item.label"
					:value="item.value"/>
			</el-select>
			<span style="margin-left: 10px">类型：</span>
			<el-select v-model="andonBasic" multiple collapse-tags style="width:200px" placeholder="andon类型">
				<el-option
					v-for="item in andonBasicList"
					:key="item.AndonCode"
					:label="item.AndonName"
					:value="item.AndonCode"/>
			</el-select>
			<span style="margin-left: 10px">日期：</span>
			<el-date-picker v-model="deliveryDate" type="daterange" range-separator="至" start-placeholder="开始日期" value-format="yyyy-MM-dd" end-placeholder="结束日期" style="width:250px"/>
			<el-button :disabled="loading" type="success" plain icon="el-icon-search" style="margin-left: 10px" @click="searchTable()">查询</el-button>
			<el-button :disabled="loading" type="warning" plain icon="el-icon-download" style="margin-left: 10px" @click="searchTable1()">导出</el-button>
			<div style="margin-top: 10px">
				<el-col :span="14">
					<el-table
						v-loading="loading"
						:data="tableData"
						:header-cell-style="{background:'#F5F5F5'}"
						element-loading-text="数据加载中"
						element-loading-spinner="el-icon-loading"
						element-loading-background="rgba(0, 0, 0, 0.2)"
						tooltip-effect="dark"
						style="width: 100%"
						height="740"
						border
						highlight-current-row
						stripe>
						<el-table-column
							type="index"
							align="center"
							width="50">
						</el-table-column>
						<el-table-column align="center" label="Andon类型" min-width="50">
							<template slot-scope="scope">
								{{ scope.row.AndonName }}
							</template>
						</el-table-column>
						<el-table-column align="center" label="呼叫时间" min-width="60">
							<template slot-scope="scope">
								{{ scope.row.TriggerTime }}
							</template>
						</el-table-column>
						<el-table-column align="center" label="响应时间" min-width="60">
							<template slot-scope="scope">
								{{ scope.row.ResponseTime }}
							</template>
						</el-table-column>
						<el-table-column align="center" label="响应时长(H)" min-width="60">
							<template slot-scope="scope">
								{{ scope.row.CountResponseTime }}
							</template>
						</el-table-column>
						<el-table-column align="center" label="解除时间" min-width="60">
							<template slot-scope="scope">
								{{ scope.row.CallOffTime }}
							</template>
						</el-table-column>
						<el-table-column align="center" label="处理时长(H)" min-width="50">
							<template slot-scope="scope">
								{{ scope.row.CountTime }}
							</template>
						</el-table-column>
					</el-table>
					<div class="block" style="margin-top: 10px;">
						<el-pagination
							v-if="!loading"
							:current-page="PageCurrent"
							:page-sizes="[50, 70, 100, 150]"
							:page-size="pageSize"
							:total="total"
							layout="total, sizes, prev, pager, next, jumper"
							@size-change="handleSizeChange"
							@current-change="handleCurrentChange"/>
					</div>
				</el-col>
				<el-col :span="10">
					<el-row>
						<div style="height: 370px;border: 1px solid #c4c4c4">
							<div class="div11" style="height: 240px">
								<el-button v-for="(item,index) in andonBasicList" :ref="'andon_' + item.AndonCode" :key="index" class="div12" @click="clickAndon(item.AndonCode)">
									{{item.AndonName}}
								</el-button>
							</div>
							<div class="div11" style="height: 100px;">
								<el-button :disabled="callEnable" style="border: none" @click="callAndon(1)">
									<img class="picture" src="../../assets/image/call.png">
								</el-button>
								<el-button :disabled="receiveEnable" style="border: none" @click="callAndon(2)">
									<img class="picture" src="../../assets/image/response.png">
								</el-button>
								<el-button :disabled="resetEnable" style="border: none" @click="callAndon(0)">
									<img class="picture" src="../../assets/image/reset.png">
								</el-button>
							</div>
							<div class="div111" style="height: 30px">
								<div class="call">呼叫</div>
								<div class="receive">响应</div>
								<div class="reset">复位</div>
							</div>
						</div>
					</el-row>
					<el-row>
						<el-card style="height: 370px;border: 1px solid #c4c4c4">
							<div id="myChart2222" style="width: 630px;height: 350px"/>
						</el-card>
					</el-row>
				</el-col>
			</div>
		</el-card>
	</div>
</template>
<script>
import { getNowTime2 } from '@/utils/tool'

export default {
  data() {
    return {
      callEnable: true,
      resetEnable: true,
      receiveEnable: true,
      PersonNum: 1,
      andonBasicList: [],
      andonBasic: [],
      andonCurrList: [],
      andonSelectList: [],
      andonCurrSelectList: [],
      opMeasureRangeData: {
        name: '',
        min1: 0,
        max1: 0,
        min2: 0,
        max2: 0
      },
      upValue: 0,
      downValue: 0,
      daliyOutPutData_X: [],
      daliyOutPutData_Y: [],
      daliyOutPutData_Average: [],
      daliyOutPutData1_X: [],
      daliyOutPutData1_Y: [],
      daliyOutPutData1_Average: [],
      opnames: [],
      opnameThis: '',
      opnameThisName: '',
      ymin: 0,
      ymax: 100,
      listOP: [],
      deliveryDate: [],
      loading: false,
      tableData: [],
      total: 0, // 总条数
      pageSize: 50, // 每页显示条数
      PageCurrent: 1 // 后台获取页
    }
  },
  props: ['opname'],
  computed: {},
  mounted() {
    this.searchTable()
  },
  created() {
    const start = new Date()
    const end = new Date(start.getTime() - 3600 * 1000 * 24 * 20)
    this.deliveryDate[1] = getNowTime2(start)
    this.deliveryDate[0] = getNowTime2(end)
    this.searchTableAndonBasic()
    this.opnameThis = this.opname
    this.searchTableOpName()
  },
  methods: {
    sendAndonMessageToMes(QtypeID, State, StationID) {

    },
    // 获取工位号
    searchTableOpName() {
      var param = []
      this.machineInfo_state = {}
      var Data = this.CreateData('11', 'AAA临工看板_主看板_查询数据', param)
      this.ExecDatabase(Data).then(response => {
        for (let i = 0; i < response.data.length; i++) {
          this.opnames.push({
            label: response.data[i].工位号 + '-' + response.data[i].工位名称,
            value: response.data[i].工位号,
            id: response.data[i].id
          })
          if (response.data[i].工位号 === this.opnameThis) {
            this.opnameThisName = response.data[i].工位号 + '-' + response.data[i].工位名称
          }
        }
      })
    },
    // 获取Andon基础表
    searchTableAndonBasic() {
      var param = []
      this.andonBasicList = []
      var Data = this.CreateData('11', 'LG_临工看板_Andon管理_基础数据查询', param)
      this.ExecDatabase(Data).then(response => {
        for (let i = 0; i < response.data.length; i++) {
          this.andonBasicList.push({
            AndonCode: response.data[i].AndonCode,
            AndonName: response.data[i].AndonName
          })
          this.andonBasic.push(response.data[i].AndonCode)
        }
        this.searchTableAndon()
      })
    },
    // 获取Andon实时表
    searchTableAndon() {
      var param = []
      this.andonCurrList = []
      param[0] = ['opname', this.opnameThis]
      var Data = this.CreateData('11', 'LG_临工看板_Andon管理_当前Andon', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length > 0) {
          this.andonCurrList = response.data
        }
        this.solveAndon()
	      this.solveButtonStatus()
      })
    },
    solveAndon() {
      this.$nextTick(() => {
        for (const andonInfo of this.andonCurrList) {
          if (andonInfo.ProcessType === 1) {
            this.$refs['andon_' + andonInfo.AndonCode][0].$el.style.color = '#f57777'
          }
          if (andonInfo.ProcessType === 2) {
            this.$refs['andon_' + andonInfo.AndonCode][0].$el.style.color = '#ecb665'
          }
          if (andonInfo.ProcessType === 0) {
            this.$refs['andon_' + andonInfo.AndonCode][0].$el.style.color = '#409EFF'
          }
        }
        const arrayList = this.andonBasicList.filter(item => !this.andonCurrList.some(ele => ele.AndonCode === item.AndonCode))
        for (const andonInfo of arrayList) {
          this.$refs['andon_' + andonInfo.AndonCode][0].$el.style.color = '#409EFF'
        }
      })
    },
	  solveButtonStatus() {
      const ValueColorMap = new Map()
      this.andonSelectList.forEach(value => {
        const color = this.$refs[value][0].$el.style.color
        ValueColorMap.set(color, color)
      })
		  const call = 'rgb(245, 119, 119)'
		  const reset = 'rgb(64, 158, 255)'
		  const receive = 'rgb(236, 182, 101)'
      if (ValueColorMap.size > 1) {
        this.callEnable = true
        this.resetEnable = true
        this.receiveEnable = true
      } else {
        if (ValueColorMap.get(reset)) {
          this.callEnable = false
          this.resetEnable = true
          this.receiveEnable = true
        } else if (ValueColorMap.get(call)) {
          this.callEnable = true
          this.resetEnable = true
          this.receiveEnable = false
        } else if (ValueColorMap.get(receive)) {
          this.callEnable = true
          this.resetEnable = false
          this.receiveEnable = true
        } else {
          this.callEnable = true
          this.resetEnable = true
          this.receiveEnable = true
        }
      }
	  },
    clickAndon(AndonCode) {
      if (this.andonSelectList.indexOf('andon_' + AndonCode) !== -1) {
        this.andonSelectList = this.andonSelectList.filter(res => { return res !== 'andon_' + AndonCode })
      } else {
        this.andonSelectList.push('andon_' + AndonCode)
      }
      let currentText = this.$refs['andon_' + AndonCode][0].$el.innerText
      if (currentText.indexOf('√') !== -1) {
        currentText = currentText.replace('√', '')
        this.$refs['andon_' + AndonCode][0].$el.innerText = currentText
        this.$refs['andon_' + AndonCode][0].$el.style.border = '1px solid #b3d8ff'
      } else {
        currentText = '√' + currentText
        this.$refs['andon_' + AndonCode][0].$el.innerText = currentText
        this.$refs['andon_' + AndonCode][0].$el.style.border = '4px solid #0080ff'
      }
      this.solveButtonStatus()
    },
    // andon呼叫 响应 解除
    callAndon(type) {
      if (this.andonSelectList.length === 0) {
        this.$message.warning('请选择要处理的andon')
        return
      }
      const andonCodeList = [1, 2, 0]
      var param = []
      const AndonCodePromise = []
      for (const andonInfo of this.andonSelectList) {
        AndonCodePromise.push(new Promise((resolve, reject) => {
          param[0] = ['AndonCode', andonInfo.replace('andon_', '')]
          param[1] = ['type', type]
          param[2] = ['opname', this.opnameThis]
          param[3] = ['PersonNum', this.PersonNum]
          var Data = this.CreateData('12', 'LG_临工看板_Andon管理_Andon呼叫解除', param)
          this.ExecDatabase(Data).then(response => {
            if (response.data[0].result === '1') {
              resolve(response.data[0].result)
            } else {
              reject(response.data[0].result)
            }
          })
        }))
      }
      const AndonCodePromiseMes = []
      for (const andonInfo of this.andonSelectList) {
        AndonCodePromiseMes.push(new Promise((resolve, reject) => {
          const url = 'apis/WebService/Andon.asmx'
          const xmlData = `<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mes="http://mes.elingong.cn/">
<soapenv:Header/>
<soapenv:Body>
<mes:Andon_Alarm>
<mes:Qtype>${andonInfo.replace('andon_', '')}</mes:Qtype>
<mes:State>${andonCodeList[type]}</mes:State>
<!--Optional:-->
<mes:StationID>${this.opnameThis}</mes:StationID>
</mes:Andon_Alarm>
</soapenv:Body>
</soapenv:Envelope>`
          this.Andon_Alarm(url, xmlData).then(response => {
            resolve(response)
          }).catch(err => {
            reject(err)
          })
        }))
      }
      Promise.all(AndonCodePromise).then(res => {
        for (const argument of this.andonSelectList) {
          let currentText = this.$refs[argument][0].$el.innerText
          currentText = currentText.replace('√', '')
          this.$refs[argument][0].$el.innerText = currentText
          this.$refs[argument][0].$el.style.border = '1px solid #b3d8ff'
        }
        this.andonSelectList = []
        this.searchTableAndon()
	      this.solveButtonStatus()
      })
      Promise.all(AndonCodePromiseMes).then(res => {
        for (const paramElement of res) {
          console.log('res', this.$x2js.xml2js(paramElement.data))
	        try {
            const xmlData = this.$x2js.xml2js(paramElement.data)
            const Flag = xmlData.Envelope.Body.Andon_AlarmResponse.Andon_AlarmResult.Flag
            const Message = xmlData.Envelope.Body.Andon_AlarmResponse.Andon_AlarmResult.Message
            console.log(Flag, Message)
            if (Flag === 'true') {
              this.$message.success(Message)
		        } else {
              this.$message.warning(Message)
		        }
          } catch (e) {
		        console.log('error', e)
          }
        }
      })
    },

    searchTable() {
      let andonCodeString = '0'
      if (!this.deliveryDate) {
        this.$message.warning('请选择查询时间')
        return
      }
      if (this.deliveryDate.length < 2) {
        this.$message.warning('请选择查询时间')
        return
      }
      if (this.deliveryDate[0] === '') {
        this.$message.warning('请选择查询时间')
        return
      }
      for (const datum of this.andonBasic) {
        andonCodeString = andonCodeString + ',' + datum
      }
      andonCodeString.substring(0, andonCodeString.lastIndexOf(','))

      this.loading = true
      this.tableData = []
      var param = []
      param[0] = ['startTime', this.deliveryDate[0]]
      param[1] = ['endTime', this.deliveryDate[1]]
      param[2] = ['PageCurrent', this.PageCurrent]
      param[3] = ['PageSize', this.pageSize]
      param[4] = ['PageCount', '1111', 'int', '1']
      param[5] = ['ItemCount', '1111', 'int', '1']
      param[6] = ['opname', this.opnameThis]
      param[7] = ['AndonCode', andonCodeString]

      var Data = this.CreateData('11', 'LG_临工看板_Andon管理_Andon呼叫历史查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length !== 0) {
          this.tableData = response.data.result
          this.total = parseInt(response.data.output[0].ItemCount)
        }
        this.loading = false
        this.searchTable2()
      })
    },
    searchTable2() {
      this.daliyOutPutData_X = []
      var param = []
      param[0] = ['startTime', this.deliveryDate[0]]
      param[1] = ['endTime', this.deliveryDate[1]]
      param[2] = ['opname', this.opnameThis]
      var Data = this.CreateData('11', 'LG_临工看板_Andon管理_Andon呼叫次数统计', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length !== 0) {
          this.daliyOutPutData_X = response.data
          this.drawLine51()
        }
      })
    },
    // 导出
    searchTable1() {
      if (!this.deliveryDate) {
        this.$message.warning('请选择查询时间')
        return
      }
      if (this.deliveryDate.length < 2) {
        this.$message.warning('请选择查询时间')
        return
      }
      if (this.deliveryDate[0] === '') {
        this.$message.warning('请选择查询时间')
        return
      }
      this.tableData1 = []
      let andonCodeString = '0'
      for (const datum of this.andonBasic) {
        andonCodeString = andonCodeString + ',' + datum
      }
      var param = []
      const blob = 'data:image/gif;base64,R0lGODlhCQACAIAAAMzMzP///yH5BAEAAAEALAAAAAAJAAIAAAIEjI9pUAA7'
      param[0] = ['startTime', this.deliveryDate[0]]
      param[1] = ['endTime', this.deliveryDate[1]]
      param[2] = ['opname', this.opnameThis]
      param[3] = ['AndonCode', andonCodeString]
      var Data = this.CreateData('2003', 'LG_临工看板_Andon管理_Andon呼叫历史导出', param)
      this.exportExcel_NPOI(Data, blob)
    },
    //
    drawLine51() {
      // 基于准备好的dom，初始化echarts实例
      this.$echarts.dispose(document.getElementById('myChart2222'))
      if (this.daliyOutPutData_X.length === 0) return
      const myChart2222 = this.$echarts.init(document.getElementById('myChart2222'))
      // 绘制图表
      myChart2222.setOption(
        {
          title: {
            text: 'Andon呼叫次数统计',
            left: 'center'
          },
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'vertical',
            left: 'left'
          },
          series: [
            {
              name: '呼叫次数',
              type: 'pie',
              radius: '70%',
              data: this.daliyOutPutData_X,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              },
	            labelLine: {
	            },
              label: {
                show: true,
                normal: {
                  formatter: function(params) {
                    console.log(params)
	                  const data = params.data
                    return data['name'].replace(' ', '').replace('Andon', '：') + '' + data['value'] + '次'
                  },
                  // formatter: '{b}: {c}次',
                  textStyle: {
                    fontWeight: 'normal',
                    fontSize: 16
                  }
                }
              }
            }
          ]
        }
      )
    },
    handleSizeChange(val) {
      this.PageCurrent = 1
      this.pageSize = val
      this.searchTable()
    },
    handleCurrentChange(val) {
      this.PageCurrent = val
      this.searchTable()
    }
  }
}
</script>
<style scoped>
	.div1{
		width: 140px;
		height: 105px;
		margin-left:15px;
		margin-top:15px;
		background: green;
		color: white;
		font-size: 25px;
	}
	.div2{
		width: 140px;
		height: 105px;
		margin-left:15px;
		margin-top:15px;
		background: #60839e;
		color: white;
		font-size: 25px;
	}
	.div11{
		width: 100%;
		display: flex;/*父元素设置flex属性*/
		align-items: center;/*垂直交叉轴居中*/
		justify-content: center;
		flex-wrap: wrap;
	}
	.div111{
		width: 100%;
		display: flex;/*父元素设置flex属性*/
		align-items: center;/*垂直交叉轴居中*/
		justify-content: center;
		flex-wrap: wrap;
	}
	/*中间部分显示故障的样式*/
	.div12{
		width: 170px;
		height: 100px;
		margin: 10px;
		font-size: 24px;
		color: #409EFF;
		background: #ecf5ff;
		border: 1px solid #b3d8ff;
	}
	/*右侧复位图片样式*/
	.picture{
		width: 100px;
		text-align: center;
		margin: 0 25px;
	}
	/*右侧文字样式*/
	.call{
		font-size: 25px;
		color: #f57777;
		width: 200px;
		text-align: center;
	}
	/*右侧文字样式*/
	.receive{
		font-size: 25px;
		color: #ecb665;
		width: 200px;
		text-align: center;
	}
	.reset{
		font-size: 25px;
		color: #409EFF;
		width: 200px;
		text-align: center;
	}
</style>
