<template>
  <div class="app-container">
		<!-- 搜索模块 -->
    <div class="filter-container">
    	<!--<span>
    		<span>{{$t("lineSide.searchForm.name")}}：</span>
    		<el-input v-model="queryParams.model.name" :placeholder='$t("common.pleaseEnter")' style="width: 150px;" size="medium"/>
    	</span>-->
    	<span>
    		<span>{{$t("resource.searchForm.startEndTime")}}：</span>
    		<el-date-picker
		      v-model="queryParams.timeRange"
		      type="daterange"
		      :picker-options="pickerOptions"
		      :range-separator='$t("common.separator")'
		      :start-placeholder='$t("common.startTime")'
		      :end-placeholder='$t("common.endTime")'
		      format="yyyy-MM-dd"
			    value-format="yyyy-MM-dd"
		      align="right">
		    </el-date-picker>
    	</span>
    	<!--<span style="margin-left: 15px;">
    		<span>{{$t("lineSide.common.type")}}：</span>
    		<el-select v-model="queryParams.model.optType" :placeholder='$t("common.pleaseSelect")' size="medium" style="width: 150px;">
        	<el-option
			      v-for="item in audioStatus"
			      :key="item.value"
			      :label="item.label"
			      :value="item.value">
			    </el-option>
      	</el-select>
    	</span>-->
      <span style="margin-left: 15px;">
	      <el-button plain type="primary" icon="el-icon-search" size="medium" @click="search">
	        {{ $t("table.search") }}
	      </el-button>
	      <el-button plain type="warning" icon="el-icon-refresh" size="medium" @click="reset">
	        {{ $t("table.reset") }}
	      </el-button>
      </span>
    </div>
    
    <!-- 功能按钮 -->
    <el-row class="filter-container">
    	<el-col>
    		<el-button v-has-permission="['warnLong:delete']" type="danger" icon="el-icon-delete" size="medium" @click="batchDelete">
	        {{ $t("table.delete") }}
	      </el-button>
    		<el-button v-has-permission="['warnLong:tags']" type="primary" icon="el-icon-plus" size="medium" @click="marking">{{ $t("developer.buttons.marking") }}</el-button>
	      <!--<el-button type="success" icon="el-icon-edit" size="medium" @click="editOne">
	        {{ $t("common.edit") }}
	      </el-button>-->
    	</el-col>
    </el-row>
	    
		<!-- 列表数据 -->
    <el-table
      :key="tableKey"
      ref="table"
      v-loading="loading"
      :data="tableData.records"
      border
      fit
      row-key="id"
      style="width: 100%;"
      @selection-change="onSelectChange"
      @cell-click="cellClick"
    >
    	<!-- 序号 -->
    	<el-table-column :label='$t("common.serialNo")' width="55px" align="center">
	      <template slot-scope="scope">
	        <div>
	          {{scope.$index+(queryParams.current - 1) * queryParams.size + 1}}
	        </div>
	      </template>
      </el-table-column>
      <!-- CheckBox -->
      <el-table-column align="center" type="selection" width="50" :reserve-selection="true" />
      <!-- 编码 -->
      <el-table-column prop="nodeNo" :label='$t("developer.table.warnLong.no")' :show-overflow-tooltip="true" width="180"></el-table-column>
      <!-- 设备 -->
      <el-table-column prop="resourceName" :label='$t("developer.table.warnLong.name")' width="100"></el-table-column>
      <!-- 报警内容 -->
      <el-table-column prop="shelvesDesc" :label='$t("developer.table.warnLong.storgeId")' width="180px">
	      <template slot-scope="{ row }">
			<span> {{row.resourceName}}-{{row.procedureName}}-{{row.instructionName}}-</span>
			<span v-if="row.feedback">{{row.feedback}}</span>
			<span else="">任务超时</span>
		  </template>
	  </el-table-column>
      <!-- 报警时间 -->
      <el-table-column prop="createTime" :label='$t("developer.table.warnLong.updateTime")' width="180px"></el-table-column>
      <!-- 是否需要人员处理 -->
      <el-table-column prop="num" :label='$t("developer.table.warnLong.num")' align="center" width="150px">
      	<template slot-scope="{ row }">
      		<el-tag v-if="row.feedback" type="success">{{$t("common.yes")}}</el-tag>
	      	<el-tag v-else type="">{{$t("common.no")}}</el-tag>
		</template>
      </el-table-column>
      <!-- 处理状态 -->
      <el-table-column prop="optType" :label='$t("developer.table.warnLong.goodsType")' align="center" width="120px">
      	<template slot-scope="{ row }">
      		    <el-tag v-if="row.status == '0'" type="failed">{{$t("developer.common.status.start")}}</el-tag>
	      	    <el-tag v-if="row.status == '1'" type="success">{{$t("developer.common.status.end")}}</el-tag>
					
		</template>
      </el-table-column>
      <!-- 处理时间 -->
      <el-table-column prop="updateTime" :label='$t("developer.table.warnLong.chuliTime")' width="180px">
	     <template slot-scope="{ row }">
	         <span v-if="row.status == '1'">{{row.updateTime}}</span>
	     </template>
	  </el-table-column>        
    </el-table>
    <pagination
      v-show="tableData.total > 0"
      :limit.sync="queryParams.size"
      :page.sync="queryParams.current"
      :total="Number(tableData.total)"
      @pagination="fetch"
    />
    <tenant-edit
      ref="edit"
      :dialog-visible="dialog.isVisible"
      :title="dialog.title"
      @close="editClose"
      @success="editSuccess"
    />
    <tenant-view
      ref="view"
      :dialog-visible="tenantViewVisible"
      @close="viewClose"
    />
    <el-dialog
      v-el-drag-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      title="预览"
      width="80%"
      top="50px"
      :visible.sync="preview.isVisible"
    >
      <el-scrollbar>
        <div v-html="preview.context" />
      </el-scrollbar>
    </el-dialog>
  </div>
</template>

<script>
	import Pagination from "@/components/Pagination"
	import TenantEdit from "./components/Edit"
	import TenantView from "./components/View"
	// 【锁定记录、出入库记录】-API
	//import lockingRecordApi from "@/api/lineSideLibrary/lockingRecord"
	import warnLogApi from "@/api/lineSideLibrary/warnLog"
	import elDragDialog from '@/directive/el-drag-dialog'
	import { downloadFile, initEnums, initDicts, initQueryParams } from '@/utils/commons'
	import axios from 'axios'
	export default {
	  name: "InOutRecord",
	  directives: { elDragDialog },
	  components: { Pagination, TenantEdit, TenantView },
	  props: {
	  },
	  data () {
	    return {
	    	audioStatus: [],
	      dialog: {
	        isVisible: false,
	        title: ""
	      },
	      preview: {
	        isVisible: false,
	        context: ''
	      },
	      tenantViewVisible: false,
	      tableKey: 0,
	      queryParams: initQueryParams({}),
	      selection: [],
	      loading: false,
	      tableData: {
	        total: 0
	      },
	      dicts: {
          NATION: {}
        },
	      enums: {
	        TenantTypeEnum: {},
	        TenantStatusEnum: {}
	      },
	      pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        }
	    }
	  },
	  // 实例已经在内存中创建好，此时data和methods已将ok,如果要操作data中的数据或是调用methods中的方法，最早只能在created中操作
	  created() {
	  	// 调用常量-审核状态
	  	this.audioStatus = this.$constWKS.OPTTYPE
	  	// 加载【字典】
	  	initDicts(['NATION'], this.dicts);
	  	// 加载列表数据
	  	this.fetch()
		},
	  computed: {
	    currentUser () {
	      return this.$store.state.account.user
	    },
	    nationList() {
        return convertEnum(this.dicts.NATION)
      }
	  },
	  mounted () {
	    
	  },
	  methods: {
	    viewClose () {
	      this.tenantViewVisible = false
	    },
	    editClose () {
	      this.dialog.isVisible = false
	    },
	    editSuccess () {
	      this.search()
	    },
	    onSelectChange (selection) {
	      this.selection = selection
	    },
	    search () {
	      this.fetch({
	        ...this.queryParams
	      })
	    },
	    reset () {
	      this.queryParams = initQueryParams({})
	      this.$refs.table.clearSort()
	      this.$refs.table.clearFilter()
	      this.search()
	    },
	    add () {
	      this.$refs.edit.type = "add"
	      this.$refs.edit.setTenant(false, this.dicts)
	      this.dialog.title = this.$t("common.add")
	      this.dialog.isVisible = true
	    },
	    singleDelete (row) {
	      this.$refs.table.clearSelection()
	      this.$refs.table.toggleRowSelection(row, true)
	      this.batchDelete()
	    },
	    batchDelete () {
	      if (!this.selection.length) {
	        this.$message({
	          message: this.$t("tips.noDataSelected"),
	          type: "warning"
	        })
	        return
	      }
	
	      this.$confirm(this.$t("developer.tips.wareTips"), this.$t("common.tips"), {
	      	distinguishCancelAndClose: true,
	        confirmButtonText: this.$t("common.confirm"),
	        cancelButtonText: this.$t("common.cancel"),
	        type: "warning"
	      }).then(() => {
	      	const ids = []
		      this.selection.forEach(item => {
		        ids.push(item.id)
		      })
		      this.delete(ids)
	      }).catch(() => {})
	    },
	    clearSelections () {
	      this.$refs.table.clearSelection()
	    },
		marking(){
		   if (!this.selection.length) {
	        this.$message({
	          message: this.$t("tips.noDataSelected"),
	          type: "warning"
	        })
	        return false
	      }
		    const ids = []
		    this.selection.forEach(item => {
		        ids.push(item.id)
		    })
		    this.updateStatus(ids)	      		
		},
		updateStatus(ids){		   
		   warnLogApi.updateStatus({ids: ids}).then(response => {
			const res = response.data
			if (res.isSuccess) {
				this.$message({
					message: '标注成功',
					type: "success"
				})
				this.search()
			}
         })
		},
	    delete (ids) {
	      warnLogApi.remove({ ids: ids }).then(response => {
	        const res = response.data
	        if (res.isSuccess) {
	          this.$message({
	            message: this.$t("tips.deleteSuccess"),
	            type: "success"
	          })
	          this.search()
	          // 清理已经删除的数据
	          this.$refs.table.clearSelection()
	        }
	      })
	    },
	    view (row) {
	      this.$refs.view.setTenant(row)
	      this.tenantViewVisible = true
	    },
	    // 【修改】表头上Btn-事件
	    editOne() {
	    	if (!this.selection.length) {
	        this.$message({
	          message: this.$t("tips.noDataSelected"),
	          type: "warning"
	        })
	        return
	      }
	    	if (this.selection.length > 1) {
	        this.$message({
	          message: this.$t("tips.mustOne"),
	          type: "warning"
	        })
	        return
	      }
	    	this.edit(this.selection[0]);
	    },
	    edit (row) {
	      this.$refs.edit.setTenant(row, this.dicts)
	      this.$refs.edit.type = "edit"
	      this.dialog.title = this.$t("common.edit")
	      this.dialog.isVisible = true
	    },
	    fetch (params = {}) {
	      this.loading = true
	      if (this.queryParams.timeRange) {
	        this.queryParams.map.createTime_st = this.queryParams.timeRange[0]
	        this.queryParams.map.createTime_ed = this.queryParams.timeRange[1]
	      }
	
	      this.queryParams.current = params.current ? params.current : this.queryParams.current
	      this.queryParams.size = params.size ? params.size : this.queryParams.size
	      // 固定参数：dataStatus = 1-入库/出库，2-解锁/锁定
	      //this.queryParams.model.dataStatus = '1'
	      warnLogApi.page(this.queryParams).then(response => {
	        const res = response.data
	        if (res.isSuccess) {
	          this.tableData = res.data
	        }
	        // eslint-disable-next-line no-return-assign
	      }).finally(() => this.loading = false)
	     
	    },
	    cellClick (row, column) {
	      if (column['columnKey'] === "operation") {
	        return
	      }
	      let flag = false
	      this.selection.forEach((item) => {
	        if (item.id === row.id) {
	          flag = true
	          this.$refs.table.toggleRowSelection(row)
	        }
	      })
	
	      if (!flag) {
	        this.$refs.table.toggleRowSelection(row, true)
	      }
	    }
	  }
	}
</script>
<style lang="scss" scoped></style>
