<template>
  <div>
    <el-card>
      <span class="show-text">数据类型:</span>
      <el-select id="selectPersonalRoleValue" v-model="DataType" multiple collapse-tags class="personal-role-value" style="width:280px;margin-right: 14px" clearable placeholder="请选择数据类型">
        <el-option
          v-for="item in DataTypes"
          :key="item.value"
          :label="item.label"
          :value="item.value"/>
      </el-select>
      <span class="show-text">采集时间:</span>
      <el-date-picker
        ref="datePick"
        v-model="collectionTime"
        :clearable="false"
        :picker-options="pickerOptions"
        name="date-picker"
        popper-class="virtual-cell-time-picker"
        value-format="yyyy-MM-dd HH:mm"
        format="yyyy-MM-dd HH:mm"
        type="datetimerange"
        range-separator="-"
        style="width: 380px;margin-right: 16px;vertical-align: top"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        @change="selectData"/>
      <el-button :disabled="loading" icon="el-icon-search" type="primary" @click="pageList=1;searchTable()">查询</el-button>
      <el-button :disabled="loading" style="margin-left: 14px;width: 150px" icon="el-icon-video-camera" type="info" @click="GoToPlay()">数据录放</el-button>
      <div style="margin-top: 26px">
        <el-table
          v-loading="loading"
          :data="tableData"
          :header-row-style= "{fontSize: '18px',fontFamily:'MiSans Demibold',height: '64px',backgroundColor:'#fff'}"
          :row-style="{fontSize: '16px',fontFamily:'MiSans Regular',height: '64px'}"
          element-loading-text="数据加载中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.2)"
          tooltip-effect="dark"
          style="width: 1201px"
          height="707"
          border
          size="mini">
          <el-table-column type="index" label=" " align="center" width="50"/>
          <el-table-column align="center" label="信号名称" width="200">
            <template slot-scope="scope">
              {{ scope.row.信号名称 }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="IEC格式" width="200">
            <template slot-scope="scope">
              {{ scope.row.IEC格式 }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="信号值" min-width="300">
            <template slot-scope="scope">
              {{ scope.row.Value }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="数据类型" width="150">
            <template slot-scope="scope">
              {{ scope.row.数据类型 }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="采集时间" width="250">
            <template slot-scope="scope">
              {{ scope.row.OperationTime }}
            </template>
          </el-table-column>
        </el-table>
        <div class="block" style="margin-top: 32px;">
          <el-pagination
            v-if="!loading"
            :current-page="pageList"
            :page-sizes="[50, 100, 200, 300]"
            :page-size="pageSize"
            :total="total"
            background
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"/>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      pickerOptions: {
        startDate: null,
        disabledDate: time => {
          if (this.pickerOptions1.startDate === undefined || this.pickerOptions1.startDate === null) {
            console.log(1)
            return time.getTime() > Date.now()
          } else {
            console.log(2)
            return time.getTime() > new Date(this.pickerOptions1.startDate.toLocaleDateString()).getTime() + 15 * 86390000 || time.getTime() < new Date(this.pickerOptions1.startDate.toLocaleDateString()).getTime() - 15 * 86390000
          }
        },
        onPick: dateRange => {
          this.pickerOptions1.startDate = dateRange.minDate
          if (dateRange.maxDate) {
            this.pickerOptions1.startDate = null
          }
        }
      },
      pickerOptions1: {
        startDate: null,
        endDate: null
      },
      DataType: [],
      robotData: {},
      DataTypes: [],
      DataTypeMap: new Map(),
      DataTypePlcMap: new Map(),
      TagName: '',
      collectionTime: [],
      loading: false,
      tableData: [],
      tableData1: [],
      tableData3: [],
      total: 0, // 总条数
      pageSize: 50, // 每页显示条数
      pageList: 1 // 后台获取页
    }
  },
  created() {
    this.searchRobotBasicData()
    this.searchPlcBasicData()
  },
  mounted() {
    // this.collectionTime[0] = new Date(new Date().toLocaleDateString()).getTime()
    // this.collectionTime[1] = new Date(new Date()).getTime()
  },
  methods: {
    selectData(e) {
      if (e === null) {
        this.pickerOptions1.startDate = null
      }
    },
    searchRobotBasicData() {
      this.DataTypeMap = new Map()
      this.DataTypeMap.set('PLC', 'PLC')
      this.DataTypes = [{ label: 'PLC数据', value: 'PLC' }]
      var param = []
      var Data = this.CreateData('11', '基础数据_机器人信息_查询', param)
      this.ExecDatabase(Data).then(response => {
        for (const argument of response.data) {
          this.robotData[argument.RobotCode] = argument.RobotName
          this.DataTypeMap.set(argument.RobotCode, argument.RobotName)
          this.DataTypes.push({
            label: argument.RobotName,
            value: argument.RobotCode
          })
        }
        for (const argument of this.DataTypes) {
          this.DataType.push(argument.value)
        }
      })
    },
    searchPlcBasicData() {
      this.DataTypePlcMap = new Map()
      var param = []
      var Data = this.CreateData('11', '基础数据_Base_SignalTable_查询', param)
      this.ExecDatabase(Data).then(response => {
        for (const argument of response.data) {
          const showName = argument.TagName
          const IEC = '【' + argument.变量类型 + '】' + argument.变量地址 + argument.变量其它
          this.DataTypePlcMap.set(argument.TagID, {
            name: showName,
            value: IEC
          })
        }
      })
    },
    // 查询
    searchTable() {
      if (this.collectionTime.length === 0) {
        this.$message.error('请选择需要查询的时间段！')
        return
      }
      this.loading = true
      this.tableData = []
      const url = '/SelectPage'

      let ProjectCode = ' '
      let OpName = ' '
      const PLCLength = this.DataType.filter(res => res === 'PLC').length
      if (this.DataType.length === this.DataTypes.length || this.DataType.length === 0) {
        OpName = ' '
        ProjectCode = ' '
      } else {
        if (PLCLength === 1) {
          ProjectCode = ProjectCode + ` ProjectCode IN ( 'PLC') `
        }
        let str = ''
        const newData = this.DataType.filter(res => res !== 'PLC')
        if (newData.length > 0) {
          for (const info of this.DataType) {
            if (info !== 'PLC') {
              str = str + `'${info}'` + ','
            }
          }
          str = str.replace(/,$/gi, '')

          OpName = ' AND OpName IN (' + str + ') '
          if (ProjectCode.replace(' ', '').length !== 0) ProjectCode = ' OR ' + ProjectCode
        } else {
          if (ProjectCode.replace(' ', '').length !== 0) ProjectCode = ' AND ' + ProjectCode
        }
      }
      const params = {
        StartTime: this.collectionTime[0],
        EndTime: this.collectionTime[1],
        PageCurrent: this.pageList,
        PageSize: this.pageSize,
        OpName: OpName,
        ProjectCode: ProjectCode
      }
      this.ExecDT_ProcessData_Post(url, params).then(response => {
        if (response.data.result.length !== 0) {
          for (let i = 0; i < response.data.result.length; i++) {
            let showInfo = this.DataTypePlcMap.get(response.data.result[i].OpName)
            const dataType = this.solveDataType(response.data.result[i].OpName, response.data.result[i].ProjectCode)
            if (response.data.result[i].ProjectCode === '机器人数据' || response.data.result[i].ProjectCode === '') {
              response.data.result[i].ProjectCode = '机器人数据'
              showInfo = {
                name: dataType,
                value: ''
              }
            }
            this.tableData.push({
              信号名称: showInfo ? showInfo.name : '',
              IEC格式: showInfo ? showInfo.value : '',
              Value: this.solveValue(response.data.result[i].Value, response.data.result[i].OpName, response.data.result[i].ProjectCode),
              数据类型: response.data.result[i].ProjectCode,
              OpName: response.data.result[i].OpName,
              OperationTime: response.data.result[i].OperationTime
            })
          }
        } else {
          this.$message.warning('暂无生产数据！')
        }
        this.total = parseInt(response.data.ItemCount)
        this.loading = false
      }).catch(res => {
        this.loading = false
        this.$message.error(res.message)
      })
      // var param = []
      // param[0] = ['开始时间', this.collectionTime[0]]
      // param[1] = ['结束时间', this.collectionTime[1]]
      // param[2] = ['PageCurrent', this.pageList]
      // param[3] = ['PageSize', this.pageSize]
      // param[4] = ['PageCount', '1111', 'int', '1']
      // param[5] = ['ItemCount', '1111', 'int', '1']
      // param[6] = ['数据类型', 1]
      // var Data = this.CreateData('11', '生产过程_查询', param)
      // this.ExecDatabase(Data).then(response => {
      //   if (response.data.result.length !== 0) {
      //     this.tableData = response.data.result
      //     for (const info of this.tableData) {
      //       info.Value = this.solveValue(info.Value, info.数据类型)
      //       if (info.数据类型 === '机器人数据') info.信号名称 = this.robotData[info.TagID]
      //     }
      //   }
      //   this.total = parseInt(response.data.output[0].ItemCount)
      //   this.loading = false
      // })
    },
    GoToPlay() {
      this.$router.push({
        name: 'DataPlayBackPage',
        params: {
          DataType: this.DataType,
          collectionTime: this.collectionTime
        }
      })
    },
    solveValue(data, type, ProjectCode) {
      let dataSolve = ''
      let dataSolve1 = ''
      if (ProjectCode === 'PLC') {
        dataSolve1 = data
      } else {
        if (data.split('|').length === 4) {
          dataSolve = data.split('|')[3]
          dataSolve1 = JSON.parse(dataSolve)
          dataSolve = {
            J1: parseFloat(dataSolve1['J1']),
            J2: parseFloat(dataSolve1['J2']),
            J3: parseFloat(dataSolve1['J3']),
            J4: parseFloat(dataSolve1['J4']),
            J5: parseFloat(dataSolve1['J5']),
            J6: parseFloat(dataSolve1['J6'])
          }
          dataSolve1 = JSON.stringify(dataSolve)
        } else {
          dataSolve1 = '机器人数据存储错误'
        }
      }
      return dataSolve1
    },
    solveDataType(type, ProjectCode) {
      let dataSolve1 = ''
      if (ProjectCode === 'PLC') {
        dataSolve1 = this.DataTypeMap.get(ProjectCode)
      } else {
        dataSolve1 = this.DataTypeMap.get(type)
      }
      return dataSolve1
    },
    // 分页
    handleSizeChange(val) {
      this.pageList = 1
      this.pageSize = val
      this.searchTable()
    },
    handleCurrentChange(val) {
      this.pageList = val
      this.searchTable()
    }
  }
}
</script>
