<template>
  <div class="app-container">
		<!-- 搜索模块 -->
    <div class="filter-container">
<!--    	<span>
    		<span>订单名称：</span>
    		<el-input v-model="queryParams.model.orderName" :placeholder='$t("common.pleaseEnter")' style="width: 150px;" size="medium"/>
    	</span>-->
    	<span style="margin-left: 15px;">
    		<span>{{$t("lineSide.searchForm.status")}}：</span>
    		<el-select v-model="queryParams.model.scanResult" :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-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='' width="50" align="center"></el-table-column>
      <el-table-column align="center" type="selection" width="50" :reserve-selection="true" />
<!--      <el-table-column prop="orderName" :label='"订单名称"' :show-overflow-tooltip="true"></el-table-column>-->
      <el-table-column prop="deviceName" :label='"设备名称"' :show-overflow-tooltip="true" ></el-table-column>
      <el-table-column prop="needToolCategory" :label='"缺少刀具类别"' :show-overflow-tooltip="true" ></el-table-column>
      <el-table-column prop="scanResult" :label='"任务状态"' :show-overflow-tooltip="true" >
        <template slot-scope="{ row }">
          <el-tag :type="getTagType(row.scanResult)">
            {{ getToolTypeText(row.scanResult) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" :label='$t("lineSide.table.toolManagement.createTime")' width="180px"></el-table-column>
      <el-table-column
        :label="$t('table.operation')"
        fixed="right"
        align="center"
        column-key="operation"
        width="140px"
      >
        <template slot-scope="{ row }">
          <el-tooltip class="item" :content='"换刀"' effect="dark" placement="top-start">
	          <i
	            class="el-icon-view table-operation"
	            style="color: #2db7f5;"
	            @click="edit(row)"
	          />
          </el-tooltip>
        </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"
      :tool-category="toolCategory"
      :device-name="deviceName"
      :plan-id="planId"
      :device-id="deviceId"
      :task-id="id"
      :scan-result="scanResult"
      @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='$t("common.preview")'
      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 toolManagementApi from "@/api/modelingCenter/toolManagement"
	import elDragDialog from '@/directive/el-drag-dialog'
  import {downloadFile, initEnums, initDicts, initQueryParams, initQueryParams0} from '@/utils/commons'
	// 加载工具类
	import { convertEnum, createTreeData } from '@/utils/utils'
	import axios from 'axios'
	export default {
	  name: "GoodsShelvesMgr",
	  directives: { elDragDialog },
	  components: { Pagination, TenantEdit, TenantView },
	  props: {
	  },
	  data () {
	    return {
	    	audioStatus: [],
	      dialog: {
	        isVisible: false,
	        title: ""
	      },
	      preview: {
	        isVisible: false,
	        context: ''
	      },
	      tenantViewVisible: false,
	      tableKey: 0,
	      queryParams: initQueryParams0({}),
	      selection: [],
	      loading: false,
	      tableData: {
	        total: 0
	      },
	      dicts: {
          NATION: {}
        },
	      enums: {
	        TenantTypeEnum: {},
	        TenantStatusEnum: {}
	      },
        toolCategory:[],
        deviceName:'',
        planId:'',
        deviceId:'',
        id:'',
        scanResult:'',
	    }
	  },
	  // 实例已经在内存中创建好，此时data和methods已将ok,如果要操作data中的数据或是调用methods中的方法，最早只能在created中操作
	  created() {
	  	// 调用常量-审核状态
	  	this.audioStatus = this.$constWKS.TOOLTASKLSIT
	  	// 加载【字典】
	  	initDicts(['NATION'], this.dicts);
	  	// 加载列表数据
	  	this.fetch()
		},
	  computed: {
	  	/* 转树形数据 */
	    optionData() {
	    	if(this.tableData.records){
	    		let cloneData = JSON.parse(JSON.stringify(this.tableData.records)) // 对源数据深度克隆
		      if(cloneData){
		      	return createTreeData(cloneData)
		      }
	    	}
	    },
	    currentUser () {
	      return this.$store.state.account.user
	    },
	    nationList() {
        return convertEnum(this.dicts.NATION)
      }
	  },
	  mounted () {

	  },
	  methods: {
	  	// 【启用/冻结】按钮-事件
	    updateActiveStatus(status){
	    	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
	      }
	    	// 传值
	    	let obj = {};
	    	obj = this.selection[0];
	    	obj.status = status;
	    	// 调用接口后的提示信息
	    	let msg = this.$t("tips.frozen")
	    	if(status == "1"){
	    		msg = this.$t("tips.enable")
	    	}
	    	toolManagementApi.update(obj).then(response => {
	        if (response.status == 200) {
	          this.$message({
	            message: msg,
	            type: "success"
	          })
	          // 重新查询列表数据
	          this.search()
	        }
	      })
	    },
	    // 【冻结】-Table的Row操作事件
	    dongJieRow(row) {
	    	// 传值
	    	let obj = {};
	    	obj = row;
	    	obj.status = "0";
	    	toolManagementApi.update(obj).then(response => {
	        if (response.status == 200) {
	          this.$message({
	            message: this.$t("tips.frozen"),
	            type: "success"
	          })
	          // 重新查询列表数据
	          this.search()
	        }
	      })
	    },
	    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.$refs.edit.list = this.tableData.records
	      this.dialog.title = this.$t("common.add")
	      this.dialog.isVisible = false
	    },
	    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
	      }

	      const readonlyIndex = this.selection.findIndex(item => item.readonly)

	      if (readonlyIndex > -1) {
	        this.$message({
	          message: this.$t("tips.systemData"),
	          type: "warning"
	        })
	        return
	      }

	      this.$confirm(this.$t("lineSide.tips.shelvsTips"), this.$t("common.tips"), {
	      	distinguishCancelAndClose: true,
	        confirmButtonText: this.$t("common.confirm"),
	        cancelButtonText: this.$t("common.cancel"),
	        type: "warning"
	      }).then(() => {
	      	const ids = []
		      let contain = false
		      this.selection.forEach(item => {
		        if (item.readonly) {
		          contain = true
		          return
		        }
		        ids.push(item.id)
		      })
		      if (contain) {
		        this.$message({
		          message: this.$t("tips.systemData"),
		          type: "warning"
		        })
		      } else {
		        this.delete(ids)
		      }
	      }).catch(() => {})
	    },
	    clearSelections () {
	      this.$refs.table.clearSelection()
	    },
	    delete (ids) {
	      toolManagementApi.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.unSelected"),
	          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) {
        if (row.status === '1' || row.status === '0'){
          this.toolCategory = row.taskNodeToolList
          this.deviceName = row.deviceName
          this.planId = row.planId
          this.deviceId = row.deviceId
          this.id = row.id
          this.scanResult = row.scanResult
          console.log("this.id:"+this.id)
          this.dialog.isVisible = true
          this.$refs.edit.fetch()
      }
	    },
	    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
	      toolManagementApi.toolTaskPage(this.queryParams).then(response => {
	        const res = response.data
          console.log(res)
	        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)
	      }
	    },
      getTagType(toolType) {
        switch (toolType) {
          case '0':
            return 'info'; // 第一种类型的标签颜色
          case '1':
            return 'warning'; // 第二种类型的标签颜色
          case '2':
            return 'success'; // 第三种类型的标签颜色
        }
      },
      getToolTypeText(toolType) {
        switch (toolType) {
          case '0':
            return "未扫描"; // 第二种类型的文本
          case '1':
            return '部分扫描'; // 第三种类型的文本
          case '2':
            return '全部扫描'; // 第四种类型的文本
          default:
            return "未扫描"
        }
      }
	  }
	}
</script>
<style lang="scss" scoped></style>
