<template>
  <div class="equipment-container">
    <el-tabs v-model="activeName" type="border-card">
      <el-tab-pane label="飞行设备" name="1">
        <el-form :inline="true" :model="searchParam" class="demo-form-inline">
          <el-form-item label="设备编号">
            <el-input clearable v-model="searchParam.equipmentSn" size="small" placeholder="请输入设备编号"
                      style="width: 200px"/>
          </el-form-item>
          <el-form-item label="设备名称">
            <el-input clearable v-model="searchParam.name" size="small" placeholder="请输入设备名称"
                      style="width: 200px"/>
          </el-form-item>
          <el-form-item label="无人机类型">
            <el-select clearable v-model="searchParam.type" size="small" placeholder="-请选择无人机类型-"
                       style="width: 150px">
              <el-option v-for="(value,key,index) in typeList" :key="key" :label="value" :value="key"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button :loading="tableLoading" @click="search" size="small" icon="el-icon-search" type="primary">搜索
            </el-button>
            <el-button @click="initSearchParam();search()" icon="el-icon-refresh-right"
                       type="primary" size="small"
                       style="background-color: #fff; border: 1px solid #ccc ; color: #666">清空
            </el-button>
          </el-form-item>
        </el-form>
        <el-table stripe ref="table" :height="tableHeight" v-loading="tableLoading"
                  :data="equipmentList"
                  size="medium"
                  border row-key="id">
          <el-table-column :index="indexMethod" label="序号" type="index" width="80" align="center"/>
          <el-table-column show-overflow-tooltip prop="equipmentSn" label="设备编号" align="center"/>
          <el-table-column min-width="100" show-overflow-tooltip prop="name" label="设备名称" align="center"/>
          <el-table-column show-overflow-tooltip prop="brand" label="品牌" align="center"/>
          <el-table-column show-overflow-tooltip prop="model" label="型号" align="center"/>
          <el-table-column min-width="100" show-overflow-tooltip prop="productSn" label="产品序列号" align="center"/>
          <el-table-column min-width="100" show-overflow-tooltip prop="flightSn" label="飞控序列号" align="center"/>
          <el-table-column min-width="100" show-overflow-tooltip prop="type" label="无人机类型" align="center">
            <template slot-scope="{row}">
              <span v-if="row.type">{{typeList[row.type]}}</span>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="任务类型" min-width="130" align="center">
            <template slot-scope="{row}">
              <el-tag :key="index" v-for="(item,index) in row.taskType.split(',')" v-if="item&&item!=='0'" :type="item==2?'success':''" size="small">{{taskTypeList[item]}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="状态" min-width="120" align="center">
            <template slot-scope="{row}">
              <span style="color: #666">{{row.statusName}}</span>
              <el-switch v-if="isAdmin||btnRule.some(btn=>btn=='status')" v-model="row.status" :active-value="1"
                         :inactive-value="2" size="small"
                         @change="changeStatus(row)"/>
            </template>
          </el-table-column>
          <el-table-column v-if="isAdmin||btnRule.some(btn=>btn=='edit'||btn=='drop')" width="100" label="操作">
            <template slot-scope="scoped">
              <el-tooltip v-if="isAdmin||btnRule.some(btn=>btn=='edit')" class="item" effect="dark" content="编辑"
                          placement="bottom">
                <el-button @click="handleEdit(scoped.row)" type="primary" size="mini" icon="el-icon-edit"/>
              </el-tooltip>
              <el-tooltip v-if="isAdmin||btnRule.some(btn=>btn=='drop')" class="item" effect="dark" content="删除"
                          placement="bottom">
                <el-button @click="handleDel(scoped.row)" type="danger" size="mini" icon="el-icon-delete"/>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div  class="page-current">
          <el-pagination
            background
            :current-page="currentPage"
            :page-size="pageSize"
            prev-text="上一页"
            next-text="下一页"
            layout="total, prev, pager, next, jumper"
            style="display: inline-block;"
            @current-change="handleCurrentChange"
            :total="count"/>
        </div>
      </el-tab-pane>
      <el-tab-pane v-if="isAdmin||btnRule.some(btn=>btn=='add')" label="添加设备" name="2">
        <equipmentForm :ruleForm="ruleForm" :typeList="typeList" :taskTypeList="taskTypeList"
                    style="width: 50%" v-if="activeName==2" @submit="submit"></equipmentForm>
      </el-tab-pane>
    </el-tabs>
    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" center :visible.sync="addDialogVisible" title="编辑设备">
      <equipmentForm v-if="addDialogVisible" :typeList="typeList" :taskTypeList="taskTypeList" ref="dialogForm" :ruleForm="ruleForm"
                  style="width: 100%" @submit="submit" @onBack="onBack"></equipmentForm>
    </el-dialog>
  </div>
</template>

<script>
  import equipmentApi from '@/api/basicData/equipment'
  import equipmentForm from './equipmentForm'
  import {mapGetters} from "vuex";

  export default {
    name: "equipment",
    data() {
      return {
        activeName: '1',
        addDialogVisible: false,
        searchParam: {
          equipmentSn: '',
          name: '',
          type: '',
        },
        ruleForm: {
          name:'',
          brand:'',
          model:'',
          productSn:'',
          flightSn:'',
          type:'',
          taskType:[],
          registerTime:'',
          status:1
        },
        typeList:{},
        taskTypeList:{},
        currentPage: 1,
        pageSize: parseInt((document.body.clientHeight - 290 - 43) / 44.5),
        count: 0,
        equipmentList: [],
        tableLoading: false,
        tableHeight: document.body.clientHeight - 290,
      }
    },
    components: {equipmentForm},
    created() {
    },
    computed: {
      ...mapGetters(["btnRule", "isAdmin"])
    },
    mounted() {
      this.tableLoading = true
      this.getAllList()
      this.getBaseData()
    },
    watch: {
      activeName() {
        this.initRuleForm()
      }
    },
    methods: {
      handleDel(row){
        this.$confirm('此操作将删除设备, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.tableLoading=true
          equipmentApi.dropEquipment({id:row.id}).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getAllList()
          }).catch(e => {
            this.tableLoading =false
          })
        }).catch(() => {
        });
      },
      indexMethod(index) {
        return (index + 1) + ((this.currentPage - 1) * this.pageSize);
      },
      getBaseData() {
        equipmentApi.getBaseData().then(res => {
          this.typeList=res.data.type_list?res.data.type_list:{}
          this.taskTypeList=res.data.task_type_list?res.data.task_type_list:{}
        }).catch(e => {
          this.typeList={}
          this.taskTypeList={}
        })
      },
      changeStatus(data) {
        var content = ''
        if (data.status === 1) {
          content = '确定要启用吗？'
        } else {
          content = '确定要禁用吗？'
        }
        this.$confirm(content, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let params = {
            status: data.status == 1 ? '1' : '2',
            id: data.id
          }
          this.tableLoading = true
          equipmentApi.setStatus(params).then(res => {
            this.$message({
              type: 'success',
              message: '操作成功！'
            })
            this.getAllList()
          }).catch(e => {
            let equipmentList = JSON.parse(JSON.stringify(this.equipmentList))
            for (let i = 0; i < equipmentList.length; i++) {
              if (equipmentList[i].id == data.id) {
                equipmentList[i].status = data.status == 1 ? 2 : 1
              }
            }
            this.equipmentList = Object.assign([], equipmentList)
            this.tableLoading = false
          })
        }).catch(() => {
          let equipmentList = JSON.parse(JSON.stringify(this.equipmentList))
          for (let i = 0; i < equipmentList.length; i++) {
            if (equipmentList[i].id == data.id) {
              equipmentList[i].status = data.status == 1 ? 2 : 1
            }
          }
          this.equipmentList = Object.assign([], equipmentList)
          this.$message({
            type: 'info',
            message: '已取消该操作！'
          })
        })
      },
      handleEdit(data, type) {
        console.log(data)
        this.initRuleForm()
        this.addDialogVisible = true
        this.$nextTick(function () {
          try {
            let child = JSON.parse(JSON.stringify(data))
            child.taskType=child.taskType.split(',')
            this.ruleForm = Object.assign({}, child)
          } catch (e) {
          }
        })
      },
      initSearchParam() {
        this.searchParam = {
          name: '',
          type: '',
        }
      },
      initRuleForm() {
        this.ruleForm = {
          name:'',
          brand:'',
          model:'',
          productSn:'',
          flightSn:'',
          type:'',
          registerTime:'',
          taskType:[],
          status:1
        }
      },
      getAllList() {
        let searchParam = JSON.parse(JSON.stringify(this.searchParam))
        searchParam.page = this.currentPage
        searchParam.pageSize = this.pageSize
        equipmentApi.getIndex(searchParam).then(res => {
          this.equipmentList = res.data.records
          this.count = res.data.total
          this.tableLoading = false
        }).catch(err => {
          this.equipmentList = []
          this.tableLoading = false
        })
      },
      search() {
        this.currentPage = 1
        this.tableLoading = true
        this.$refs.table.bodyWrapper.scrollTop = 0;
        this.getAllList()
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.tableLoading = true
        this.$refs.table.bodyWrapper.scrollTop = 0;
        this.getAllList()
      },
      submit(type) {
        if (type == 1) {
          this.activeName='1'
          this.search()
        } else {
          this.tableLoading = true
          this.$refs.table.bodyWrapper.scrollTop = 0;
          this.getAllList()
          this.addDialogVisible = false
        }
      },
      onBack() {
        this.initRuleForm()
        this.addDialogVisible = false
      }
    }
  }
</script>

<style lang="less">
  .equipment-container {
    width: 100%;

    .el-input.is-disabled .el-input__inner {
      background-color: #fff !important;
      color: #333 !important;
    }
  }
</style>
