<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="table.getdataListParm.deptName" clearable placeholder="部门" class="filter-item" style="width:140px;">
        <el-option v-for="item in downList.deptList" :key="item.id" :label="item.name" :value="item.name" />
      </el-select>
      <tree-select
        v-model="table.getdataListParm.eqClassId"
        :height="200"
        :width="300"
        size="small"
        class="typeSelect"
        :data="equipmentCategory.list"
        :disabled="equipmentCategory.disabled"
        :default-props="equipmentCategory.defaultProps"
        :node-key="equipmentCategory.nodeKey"
        :placeholder="equipmentCategory.placeholder"
        :checked-keys="equipmentCategory.defaultCheckedKeys"
        style="display: inline-block;top: -3px;"
        @popoverHide="popoverHide"
      />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="form_search">搜索</el-button>
    </div>
    <div class="operation">
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="form_add">新增</el-button>
    </div>
    <el-table
      slot="reference"
      border
      :data="table.list"
      header-align="center"
      :row-style="rowStyle"
      :cell-style="cellStyle"
      class="elTable"
    >
      <el-table-column label="部门" min-width="130px" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.NoEdit || scope.row.isDispaly== false">{{ scope.row.deptName }}</span>
          <el-select v-else v-model="scope.row.deptName" placeholder="部门" style="width:98%;" @change="(value)=> {changeDept(value, scope.row)}">
            <el-option v-for="item in downList.deptList" :key="item.id" :label="item.name" :value="item.name" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="用途" min-width="130px" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.NoEdit || scope.row.isDispaly== false">{{ scope.row.use }}</span>
          <el-input v-else v-model="scope.row.use" />
        </template>
      </el-table-column>
      <el-table-column label="设备类别" min-width="240px" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.NoEdit || scope.row.isDispaly== false">{{ scope.row.typeName }}</span>
          <tree-select
            v-else
            v-model="scope.row.eqClassId"
            size="small"
            :width="200"
            :display="scope.row.dispaly"
            :data="equipmentCategory.list"
            :disabled="equipmentCategory.disabled"
            :default-props="equipmentCategory.defaultProps"
            :node-key="equipmentCategory.nodeKey"
            :placeholder="equipmentCategory.placeholder"
            :checked-keys="equipmentCategory.defaultCheckedKeys"
            style="display: inline-block;"
            @popoverHide="popoverHide2"
          />
          </tree-select>
        </template>
      </el-table-column>
      <el-table-column v-for="(item,index) in table.tablelist" :key="index" align="center" :property="item.property" :label="item.label" min-width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.NoEdit">{{ scope.row[scope.column.property] }}</span>
          <el-input v-if="scope.row.Edit" v-model="scope.row[scope.column.property]" type="number" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="{row}">
          <el-button v-if="row.isCreate" :disabled="isokDisable" type="success" size="mini" @click="add_dialog_save(row)">保存</el-button>
          <el-button v-if="row.isCreate" type="danger" size="mini" @click="createCancel(row)">取消</el-button>
          <el-button v-if="row.isUpdate" type="success" size="mini" @click="form_edit(row)">编辑</el-button>
          <el-button v-if="row.isUpdateSave" :disabled="isokDisable" type="success" size="mini" @click="edit_dialog_save(row)">保存</el-button>
          <el-button v-if="row.isUpdateSave" type="danger" size="mini" @click="updateCancel(row)">取消</el-button>
          <el-button v-if="row.isUpdate" type="danger" size="mini" @click="handleRowDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="table.total>0" :total="table.total" :page.sync="table.getdataListParm.offset" :limit.sync="table.getdataListParm.pagecount" @pagination="getList" />

  </div>
</template>

<script>

import { GetDataByName, Equipment, PastureDepartment, updateAndInster, getRecuData } from '@/api/common'
import Pagination from '@/components/Pagination'
import { MessageBox } from 'element-ui'
import TreeSelect from '@/components/TreeSelect'
export default {
  name: 'AssetStandardManagement',
  components: { Pagination, TreeSelect },
  data() {
    return {
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' },
      equipmentCategory: {
        getdataListParm: { name: 'getAssetTypeList', idname: 'id', params: [-1] },
        list: [], placeholder: '设备类别', nodeKey: 'id', defaultCheckedKeys: [], disabled: false,
        defaultProps: { children: 'children', label: 'typeName' }, display: 'none'
      },
      downList: {
        deptParm: { name: 'getDepatmentOnlyName' },
        deptList: []
      },
      table: {
        tableKey: 0, list: [], tablelist: [], total: 0, listLoading: true, idsArray: [], deptEnableList: [], deptNameArray: [], propertyArray: [],
        getdataListParm: {
          deptName: '', eqClassId: '', page: 1, offset: 1, pagecount: 10, returntype: 'Map', parammaps: {}
        }
      },
      postDataParm: {},
      isokDisable: false
    }
  },
  created() {
    this.getDownDeptList()
    this.getEquipmentCategoryList()
    this.getList()
  },
  methods: {
    getDownDeptList() {
      GetDataByName(this.downList.deptParm).then(response => {
        if (response.data.list !== null) {
          this.downList.deptList = response.data.list
        } else {
          this.downList.deptList = []
        }
      })
    },
    getEquipmentCategoryList() {
      getRecuData(this.equipmentCategory.getdataListParm).then(response => {
        if (response.data.list !== null) {
          this.equipmentCategory.list = response.data
        } else {
          this.equipmentCategory.list = []
        }
      })
    },
    popoverHide(checkedIds, checkedData) {
      if (checkedIds !== null) {
        if (checkedData.children === undefined) {
          this.table.getdataListParm.eqClassId = checkedData.eqClassId
        } else {
          this.equipmentCategory.defaultCheckedKeys = []
          this.table.getdataListParm.eqClassId = ''
          this.$message({ type: 'warning', message: '请选择具体设备类型' })
        }
      } else {
        this.equipmentCategory.defaultCheckedKeys = []
        this.table.getdataListParm.eqClassId = ''
      }
    },
    getList() {
      this.table.listLoading = true
      Equipment(this.table.getdataListParm).then(response => {
        if (response.data.list !== null) {
          console.log('table数据', response.data.list)
          this.table.tablelist = response.data.list[0]
          this.table.idsArray = []
          for (let i = 0; i < this.table.tablelist.length; i++) {
            this.table.idsArray.push(this.table.tablelist[i].id)
          }
          this.table.list = response.data.list[1]
          for (let i = 0; i < this.table.list.length; i++) {
            this.$set(this.table.list[i], 'Edit', false) // 编辑
            this.$set(this.table.list[i], 'NoEdit', true) // 不可编辑/输入
            this.$set(this.table.list[i], 'isCreate', false) // 新增操作
            this.$set(this.table.list[i], 'isUpdate', true) // 编辑操作
            this.$set(this.table.list[i], 'isUpdateSave', false) // 编辑保存
            this.$set(this.table.list[i], 'isDispaly', false)
            this.$set(this.table.list[i], 'dispaly', 'none')
          }
          this.table.pageNum = response.data.pageNum
          this.table.pageSize = response.data.pageSize
          this.table.total = response.data.total
        } else {
          this.table.tablelist = []
          this.table.list = []
        }
        setTimeout(() => {
          this.table.listLoading = false
        }, 100)
      })
    },
    form_search() {
      this.table.listLoading = true
      this.table.getdataListParm.offset = 1
      this.getList()
    },
    form_add() {
      console.log('新增')
      for (let i = 0; i < this.table.list.length; i++) {
        if (this.table.list[i].Edit === true) {
          this.$message({ type: 'error', message: '当前内容未保存，请点击取消或保存继续进行操作', duration: 2000 })
          return false
        }
      }

      var obj = {}
      for (let i = 0; i < this.table.tablelist.length; i++) {
        obj.myId = (new Date()).valueOf()
        obj.Edit = true
        obj.NoEdit = false
        obj.isCreate = true
        obj.isUpdate = false
        obj.isUpdateSave = false
        obj.isDispaly = true
        obj.display = 'block'
        obj.deptName = ''
        obj.use = ''
        obj.typeName = ''
        obj.eqClassId = ''
        obj.eqCode = ''
        obj.typeName = ''
        obj[this.table.tablelist[i].property] = ''
        var a = i + 1
        obj['pastureId' + a] = this.table.tablelist[i].id
      }
      this.table.list.unshift(obj)
    },
    changeDept(item, row) {
      // console.log(item, row, this.table.idsArray)
      this.postDataParm = {}
      this.postDataParm.param = {}
      this.postDataParm.param.ids = this.table.idsArray.toString()
      this.postDataParm.param.deptName = row.deptName
      PastureDepartment(this.postDataParm).then(response => {
        this.table.deptEnableList = response.data
        this.table.deptNameArray = []
        this.table.propertyArray = []
        console.log(response.data, 'response.data')
        for (var i = 0; i < response.data.length; i++) {
          if (response.data[i].enable == 0) {
            console.log(this.table.tablelist, 'this.table.tablelist')
            for (var j = 0; j < this.table.tablelist.length; j++) {
              if (response.data[i].id == this.table.tablelist[j].id) {
                console.log(this.table.tablelist[j].label)
                this.table.deptNameArray.push(this.table.tablelist[j].label)
                this.table.propertyArray.push(this.table.tablelist[j].property)
              }
            }
          }
        }
        console.log(this.table.deptNameArray, 'this.table.deptNameArray')
        console.log(this.table.propertyArray, 'this.table.propertyArray')
      })
    },
    popoverHide2(checkedIds, checkedData) {
      console.log(checkedIds, checkedData)
      if (checkedIds !== null) {
        if (checkedData.children == undefined) {
          this.table.list[0].eqClassId = checkedData.eqClassId
          this.table.list[0].eqCode = checkedData.typeCode
          this.table.list[0].typeName = checkedData.NewName
        } else {
          this.table.list[0].eqClassId = ''
          this.table.list[0].eqCode = ''
          this.table.list[0].typeName = ''
          this.$message({ type: 'warning', message: '请选择具体设备类型' })
        }
      } else {
        this.table.list[0].eqClassId = ''
        this.table.list[0].eqCode = ''
        this.table.list[0].typeName = ''
      }
    },
    add_dialog_save(row) {
      console.log('新增保存', row)
      console.log(this.table.propertyArray, 'this.table.propertyArray')
      console.log(this.table.deptNameArray, 'this.table.deptNameArray')
      console.log(this.table.tablelist, 'this.table.tablelist')
      for (let i = 0; i < this.table.tablelist.length; i++) {
        // if(row[this.table.tablelist[i].property])
        if (row[this.table.tablelist[i].property] == '') {
          row[this.table.tablelist[i].property] = 0
        }
      }

      if (row.deptName == '') {
        this.$message({ type: 'error', message: '部门必填', duration: 2000 })
        return false
      }
      if (row.eqClassId == '') {
        this.$message({ type: 'error', message: '设备类别必填', duration: 2000 })
        return false
      }

      MessageBox.confirm('以下牧场' + this.table.deptNameArray + '与部门不匹配，保存后会置零，是否保存？', '提示', {
        confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        for (let i = 0; i < this.table.propertyArray.length; i++) {
          row[this.table.propertyArray[i]] = 0
        }
        this.postDataParm = {}
        this.postDataParm.check = 'insert'
        this.postDataParm.param = {}
        this.postDataParm.param = row
        updateAndInster(this.postDataParm).then(response => {
          if (response.msg !== 'fail') {
            this.$notify({ title: '成功', message: '新增成功', type: 'success', duration: 2000 })
            this.getList()
          } else {
            this.$notify({ title: '失败', message: '新增失败-' + response.data, type: 'danger', duration: 2000 })
          }
        })
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消' })
      })
    },
    createCancel(row) {
      for (let i = 0; i < this.table.list.length; i++) {
        if (row.myId === this.table.list[i].myId) {
          var listIndex = this.table.list.indexOf(this.table.list[i])
        }
        if (listIndex > -1) {
          this.table.list.splice(listIndex, 1)
          return
        }
      }
    },
    form_edit(row) {
      for (let i = 0; i < this.table.list.length; i++) {
        if (this.table.list[i].Edit == true) {
          this.$message({ type: 'error', message: '当前内容未保存，请点击取消或保存继续进行操作', duration: 2000 })
          return false
        }
      }
      row.Edit = true
      row.NoEdit = false
      row.isCreate = false
      row.isUpdate = false
      row.isUpdateSave = true
      row.dispaly = 'none'
      row.isDispaly = false
    },
    edit_dialog_save(row) {
      this.postDataParm = {}
      this.postDataParm.check = 'update'
      this.postDataParm.param = {}
      this.postDataParm.param = row
      console.log('编辑保存', this.postDataParm)
      updateAndInster(this.postDataParm).then(response => {
        if (response.msg !== 'fail') {
          this.getList()
          this.$notify({ title: '成功', message: '成功', type: 'success', duration: 2000 })
        } else {
          this.$notify({ title: '失败', message: '失败-' + response.data, type: 'danger', duration: 2000 })
        }
      })
    },
    updateCancel(row) {
      row.Edit = false
      row.NoEdit = true
      row.isCreate = false
      row.isUpdate = true
      row.isUpdateSave = false
      this.getList()
    },
    handleRowDelete(row) {
      MessageBox.confirm('是否确认删除此信息?', {
        confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        this.postDataParm = {}
        this.postDataParm.check = 'delete'
        this.postDataParm.param = {}
        this.postDataParm.param = row
        updateAndInster(this.postDataParm).then(response => {
          if (response.msg !== 'fail') {
            this.getList()
            this.$notify({ title: '成功', message: '删除成功', type: 'success', duration: 2000 })
          } else {
            this.$notify({ title: '失败', message: '删除失败-' + response.data, type: 'danger', duration: 2000 })
          }
        })
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  .operation{margin-bottom: 10px;}
</style>
