<template>
  <div class="app-container">
    <div class="search">
      <el-input v-model="table.getdataListParm.parammaps.Code" :placeholder="$t('driver.sbcode')" style="width: 180px;" class="filter-item" clearable />
      <el-input v-model="table.getdataListParm.parammaps.name" :placeholder="$t('driver.sbname')" style="width: 180px;" class="filter-item" clearable />
      <el-select v-model="table.getdataListParm.parammaps.enable" filterable :placeholder="$t('formulationEvaluation.sfqy')" class="filter-item" style="width: 120px;" clearable>
        <el-option v-for="item in enableList" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-button class="successBorder" @click="form_search">{{$t('common.query')}}</el-button>
      <el-button class="successBorder" @click="handleRefresh">{{$t('common.reset')}}</el-button>
    </div>
    <div class="operation">
      <el-button v-if="isRoleEdit" class="success" icon="el-icon-plus" @click="handleCreate">{{$t('formulationEvaluation.add')}}</el-button>
      <el-button v-if="isRoleEdit" class="danger" icon="el-icon-delete" @click="form_delete">{{$t('formulationEvaluation.del')}}</el-button>
    </div>
    <div class="table">
      <el-form ref="form" :rules="table.rules" :model="table">
        <el-table
          :key="table.tableKey"
          v-loading="table.listLoading"
          :element-loading-text="$t('common.tableMsg')"
          :data="table.list"
          border
          fit
          highlight-current-row
          style="width: 100%;"
          :row-style="rowStyle"
          :cell-style="cellStyle"
          class="elTable table-fixed"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" align="center" width="50" />
          <el-table-column :label="$t('formulationEvaluation.xh')" align="center" type="index" width="50px">
            <template slot-scope="scope">
              <span v-if="table.pageNum">{{ scope.$index + (table.pageNum-1) * table.pageSize + 1 }}</span>
              <span v-else>1</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('driver.sbtype')" min-width="110px" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.NoEdit">{{ scope.row.tclassname }}</span>
              <el-select v-if="scope.row.Edit" v-model="scope.row.tclassid" @change="changeTclass">
                <el-option v-for="item in equipmentTypeList" :key="item.id" :label="item.label" :value="item.id" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column :label="$t('driver.sbcode')" min-width="110px" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.NoEdit">{{ scope.row.Code }}</span>
              <el-input v-if="scope.row.Edit" v-model="scope.row.Code"
:placeholder="$t('supplier.zf1')" type="textarea" :autosize="{ minRows: 1.3, maxRows: 4}" maxlength="32" style="width:80%;padding:10px 0;" />
            </template>
          </el-table-column>
          <el-table-column :label="$t('driver.sbname')" min-width="110px" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.NoEdit">{{ scope.row.name }}</span>
              <el-input v-if="scope.row.Edit" v-model="scope.row.name" type="textarea" :autosize="{ minRows: 1.3, maxRows: 4}" style="width:80%;padding:10px 0;" maxlength="32" />
            </template>
          </el-table-column>
          <el-table-column :label="$t('driver.sjcjkbh')" min-width="110px" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.NoEdit">{{ scope.row.infoCode }}</span>
              <el-input v-if="scope.row.Edit" v-model="scope.row.infoCode" type="number" step="0.01" style="width:80%;padding:10px 0;" />
            </template>
          </el-table-column>
          <el-table-column :label="$t('formulationEvaluation.remark')" min-width="110px" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.NoEdit">{{ scope.row.remark }}</span>
              <el-input v-if="scope.row.Edit" v-model="scope.row.remark" type="textarea" :autosize="{ minRows: 1.3, maxRows: 4}" style="width:95%;padding:10px 0;" />
            </template>
          </el-table-column>
          <el-table-column :label="$t('formulationEvaluation.sfqy')" min-width="110px" align="center">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.enable" :disabled="scope.row.NoEdit==true" active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0" @change="handleEnableChange(scope.$index, scope.row)" />
            </template>
          </el-table-column>
          <el-table-column  :label="$t('errorAnalysis.cz')" align="center" width="80" class-name="small-padding fixed-width" fixed="right">
            <template slot-scope="{row}">
              <!-- 新增 -->
              <el-button v-if="row.isCreate" :disabled="isokDisable" icon="el-icon-folder-checked" class="miniSuccess" @click="createData(row)" />
              <span v-if="row.isCreate" class="centerSpan">|</span>
              <el-button v-if="row.isCreate" class="minCancel" icon="el-icon-close" @click="createCancel(row)" />
              <!-- 编辑 -->
              <el-button v-if="row.isUpdate && isRoleEdit" class="miniSuccess" icon="el-icon-edit-outline" @click="handleUpdate(row)" />
              <span v-if="row.isUpdate && isRoleEdit" class="centerSpan">|</span>
              <el-button v-if="row.isUpdate && isRoleEdit" class="miniDanger" icon="el-icon-delete" @click="handleRowDelete(row)" />
              <!-- 编辑保存 -->
              <el-button v-if="row.isUpdateSave" :disabled="isokDisable" icon="el-icon-folder-checked" class="miniSuccess" @click="updateData(row)" />
              <span v-if="row.isUpdateSave" class="centerSpan">|</span>
              <el-button v-if="row.isUpdateSave" class="minCancel" icon="el-icon-close" @click="updateCancel(row)" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <pagination v-show="table.total>=0" :total="table.total" :page.sync="table.getdataListParm.offset" :limit.sync="table.getdataListParm.pagecount" @pagination="getList" />
    </div>
  </div>

</template>

<script>
import { GetDataByName, PostDataByName, failproccess, ExecDataByConfig, checkButtons } from '@/api/common'
import Cookies from 'js-cookie'
import Pagination from '@/components/Pagination'
import { MessageBox } from 'element-ui'
export default {
  name: 'ForkliftManagement',
  components: { Pagination },
  data() {
    return {
      isRoleEdit: [],
      enableList: this.$t('driver.enableList'),
      equipmentTypeList: this.$t('driver.equipmentTypeList'),
      getdownListParm: {
        name: 'getDictByName',
        page: 1,
        offset: 1,
        pagecount: '',
        returntype: 'Map',
        parammaps: {
          dictname: '其他设备管理'
        }
      },
      table: {
        rules: {
          name: { type: 'string', required: true, message: '必填字段', trigger: 'change' }
        },
        getdataListParm: {
          name: 'getTmrEquipment',
          page: 1,
          offset: 1,
          pagecount: parseInt(Cookies.get('pageCount')),
          returntype: 'Map',
          parammaps: {
            pastureId: Cookies.get('pastureid'),
            Code: '',
            tclassname: '',
            enable: ''
          }
        },
        tableKey: 0,
        list: [],
        total: 0,
        listLoading: true,
        temp: {}
      },
      requestParam: {},
      isokDisable: false,
      selectList: [],
      rowStyle: { maxHeight: 30 + 'px', height: 30 + 'px' },
      cellStyle: { padding: 0 + 'px' }

    }
  },

  created() {
    this.getList()
    this.getButtons()
    this.getDownList()
  },

  methods: {
    getDownList() {
      GetDataByName(this.getdownListParm).then(response => {
        this.equipmentTypeList = response.data.list
      })
    },
    getButtons() {
      const Edit = 'ForkliftManagement'
      const isRoleEdit = checkButtons(JSON.parse(sessionStorage.getItem('buttons')), Edit)
      this.isRoleEdit = isRoleEdit
    },
    getList() {
      this.table.listLoading = true
      GetDataByName(this.table.getdataListParm).then(response => {
        if (response.data  && response.data.list ) {
          for (let i = 0; i < response.data.list.length; i++) {
            this.$set(response.data.list[i], 'Edit', false) // 编辑
            this.$set(response.data.list[i], 'NoEdit', true) // 不可编辑/输入
            this.$set(response.data.list[i], 'isCreate', false) // 新增操作
            this.$set(response.data.list[i], 'isUpdate', true) // 编辑操作
            this.$set(response.data.list[i], 'isUpdateSave', false) // 编辑保存
          }
          this.table.list = response.data.list
          this.table.pageNum = response.data.pageNum
          this.table.pageSize = response.data.pageSize
        } else {
          this.table.list = []
        }
        this.table.total = response.data.total
        setTimeout(() => {
          this.table.listLoading = false
        }, 100)
      })
    },
    handleEnableChange() {
      console.log('点击了是否启用')
    },
    changeTclass(item) {
      this.table.temp.tclassname = this.equipmentTypeList.find(obj => obj.id == item).name
      console.log(this.table.temp)
    },
    form_search() {
      console.log('点击了查询')
      this.table.getdataListParm.offset = 1
      this.getList()
    },
    handleRefresh() {
      console.log('点击了重置')
      this.table.getdataListParm.parammaps.Code = ''
      this.table.getdataListParm.parammaps.name = ''
      this.table.getdataListParm.parammaps.enable = ''
      this.table.getdataListParm.offset = 1
      this.getList()
    },

    handleCreate() {
      console.log('点击了新增')
      // 编辑true/不可编辑false
      // 新增操true,编辑false，编辑保存false
      for (let i = 0; i < this.table.list.length; i++) {
        if (this.table.list[i].Edit == true) {
          this.$message({ type: 'error', message: this.$t('driver.messageNote'), duration: 2000 })
          return false
        }
      }
      this.table.list.unshift({ 'myId': (new Date()).valueOf(), 'Edit': true, 'NoEdit': false, 'isCreate': true, 'isUpdate': false, 'isUpdateSave': false, 'enable': 1, 'Code': '', 'name': '', 'infoCode': '' })
    },
    createData(row) {
      console.log('点击了新增保存')
      this.table.temp.pastureId = Cookies.get('pastureid')
      this.table.temp.Code = row.Code
      this.table.temp.name = row.name
      this.table.temp.infoCode = row.infoCode
      this.table.temp.enable = row.enable
      this.table.temp.remark = row.remark
      this.table.temp.tclassid = row.tclassid
      if (this.table.temp.tclassid == '' && this.table.temp.Code == '' && this.table.temp.name == '' && this.table.temp.infoCode == '') {
        this.$message({ type: 'error', message: '设备类型/设备编号/设备名称/数据采集卡编号不能为空', duration: 2000 })
        return false
      } else if (this.table.temp.Code == '' && this.table.temp.name == '' && this.table.temp.infoCode == '') {
        this.$message({ type: 'error', message: '设备编号/设备名称/数据采集卡编号不能为空', duration: 2000 })
        return false
      } else if (this.table.temp.name == '' && this.table.temp.infoCode == '') {
        this.$message({ type: 'error', message: '设备名称/数据采集卡编号不能为空', duration: 2000 })
        return false
      } else if (this.table.temp.tclassid == '') {
        this.$message({ type: 'error', message: '设备类型不能为空', duration: 2000 })
        return false
      } else if (this.table.temp.name == '') {
        this.$message({ type: 'error', message: '设备名称不能为空', duration: 2000 })
        return false
      } else if (this.table.temp.Code == '') {
        this.$message({ type: 'error', message: '设备编号不能为空', duration: 2000 })
        return false
      } else if (this.table.temp.infoCode == '') {
        this.$message({ type: 'error', message: '数据采集卡编号不能为空', duration: 2000 })
        return false
      }
      const infoCode = /^([0-9]|(1[0-5]))$/
      if (!infoCode.test(parseInt(this.table.temp.infoCode))) {
        this.$message({ type: 'error', message: '数据采集卡请输入0-15之间整数', duration: 2000 })
        return false
      }

      const pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]")
      console.log(this.table.temp.Code)
      if (pattern.test(this.table.temp.Code)) {
        this.$message({ type: 'error', message: '设备编号不可输入特殊字符', duration: 2000 })
        return false
      }
      if (pattern.test(this.table.temp.name)) {
        this.$message({ type: 'error', message: '设备名称不可输入特殊字符', duration: 2000 })
        return false
      }
      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.requestParam.name = 'insertTmrEquipment'
      this.requestParam.parammaps = this.table.temp
      PostDataByName(this.requestParam).then(response => {
        console.log('新增保存发送参数', this.requestParam)
        if (response.msg !== 'fail') {
          this.$notify({ title: this.$t('common.succes'), message: this.$t('driver.saveSuccess'), type: 'success', duration: 2000 })
          this.getList()
        } else {
          const isRepeat = new RegExp('Duplicate entry :code')
          const isRepeat2 = new RegExp('Duplicate entry :infocode')
          if (isRepeat.test(response.data)) {
            this.$notify({ type: 'error', message: '设备编号不可重复，请重新录入', duration: 2000 })
            return false
          }
          if (isRepeat2.test(response.data)) {
            this.$notify({ type: 'error', message: '数据采集编号不可重复，请重新录入', duration: 2000 })
            return false
          }
          this.$notify({ title: this.$t('driver.saveFail'), message: response.data, type: 'warning', duration: 2000 })
        }
      })
    },
    createCancel(row) {
      console.log('点击了新增取消')
      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
        }
      }
    },
    handleUpdate(row) {
      for (let i = 0; i < this.table.list.length; i++) {
        if (this.table.list[i].Edit == true) {
          this.$message({ type: 'error', message: this.$t('driver.messageNote'), duration: 2000 })
          return false
        }
      }
      // 编辑true,不可编辑false
      row.Edit = true
      row.NoEdit = false
      // 新增false,编辑false,编辑保存true
      row.isCreate = false
      row.isUpdate = false
      row.isUpdateSave = true
    },
    updateData(row) {
      console.log('点击了编辑保存')
      this.table.temp.pastureId = Cookies.get('pastureid')
      this.table.temp.Code = row.Code
      this.table.temp.name = row.name
      this.table.temp.infoCode = row.infoCode
      this.table.temp.enable = row.enable
      this.table.temp.remark = row.remark
      this.table.temp.tclassid = row.tclassid
      this.table.temp.tclassname = row.tclassname
      this.table.temp.id = row.id
      if (this.table.temp.tclassid == '' && this.table.temp.Code == '' && this.table.temp.name == '' && this.table.temp.infoCode == '') {
        this.$message({ type: 'error', message: '设备类型/设备编号/设备名称/数据采集卡编号不能为空', duration: 2000 })
        return false
      } else if (this.table.temp.Code == '' && this.table.temp.name == '' && this.table.temp.infoCode == '') {
        this.$message({ type: 'error', message: '设备编号/设备名称/数据采集卡编号不能为空', duration: 2000 })
        return false
      } else if (this.table.temp.name == '' && this.table.temp.infoCode == '') {
        this.$message({ type: 'error', message: '设备名称/数据采集卡编号不能为空', duration: 2000 })
        return false
      } else if (this.table.temp.tclassid == '') {
        this.$message({ type: 'error', message: '设备类型不能为空', duration: 2000 })
        return false
      } else if (this.table.temp.name == '') {
        this.$message({ type: 'error', message: '设备名称不能为空', duration: 2000 })
        return false
      } else if (this.table.temp.Code == '') {
        this.$message({ type: 'error', message: '设备编号不能为空', duration: 2000 })
        return false
      } else if (this.table.temp.infoCode == '') {
        this.$message({ type: 'error', message: '数据采集卡编号不能为空', duration: 2000 })
        return false
      }
      const infoCode = /^([0-9]|(1[0-5]))$/
      if (!infoCode.test(parseInt(this.table.temp.infoCode))) {
        this.$message({ type: 'error', message: '数据采集卡请输入0-15之间整数', duration: 2000 })
        return false
      }

      const pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]")
      console.log(this.table.temp.Code)
      if (pattern.test(this.table.temp.Code)) {
        this.$message({ type: 'error', message: '设备编号不可输入特殊字符', duration: 2000 })
        return false
      }
      if (pattern.test(this.table.temp.name)) {
        this.$message({ type: 'error', message: '设备名称不可输入特殊字符', duration: 2000 })
        return false
      }

      this.isokDisable = true
      setTimeout(() => {
        this.isokDisable = false
      }, 1000)
      this.requestParam.name = 'updateTmrEquipment'
      this.requestParam.parammaps = this.table.temp
      PostDataByName(this.requestParam).then(response => {
        console.log('新增保存发送参数', this.requestParam)
        if (response.msg !== 'fail') {
          this.$notify({ title: this.$t('common.succes'), message: this.$t('driver.saveSuccess'), type: 'success', duration: 2000 })
          this.getList()
        } else {
          const isRepeat = new RegExp('Duplicate entry :code')
          const isRepeat2 = new RegExp('Duplicate entry :infocode')
          if (isRepeat.test(response.data)) {
            this.$notify({ type: 'error', message: '设备编号不可重复，请重新录入', duration: 2000 })
            return false
          }
          if (isRepeat2.test(response.data)) {
            this.$notify({ type: 'error', message: '数据采集编号不可重复，请重新录入', duration: 2000 })
            return false
          }
          this.$notify({ title: this.$t('driver.saveFail'), message: response.data, type: 'warning', duration: 2000 })
        }
      })
    },
    updateCancel(row) {
      console.log('点击了编辑取消')
      // 编辑false,不可编辑true
      row.Edit = false
      row.NoEdit = true
      // 新增false,编辑true,编辑保存false
      row.isCreate = false
      row.isUpdate = true
      row.isUpdateSave = false
      this.getList()
    },

    handleRowDelete(row) {
      console.log('点击了行内删除')
      MessageBox.confirm( this.$t('common.delMsg'), {
        confirmButtonText: this.$t('common.confirm'), confirmButtonText: this.$t('common.cancel'), type: 'warning'
      }).then(() => {
        this.selectList = []
        this.requestParam = {}
        this.requestParam.name = 'deleteTmrEquipment'
        this.requestParam.parammaps = {}
        this.requestParam.parammaps.id = row.id
        PostDataByName(this.requestParam).then(response => {
          if (response.msg === 'fail') {
            this.$notify({ title: this.$t('common.delfail'), message: response.data, type: 'warning', duration: 2000 })
          } else {
            this.$notify({ title: this.$t('common.succes'),message: this.$t('common.delSuccess'), type: 'success', duration: 2000 })
            this.getList()
          }
        })
      }).catch(() => {
        this.$message({ type: 'info', message: this.$t('common.cancelMsg') })
      })
    },
    handleSelectionChange(val) {
      console.log('勾选数据', val)
      this.selectList = val
    },
    form_delete() {
      console.log('点击了删除')
      if (this.selectList.length == 0) {
        this.$message({ type: 'error', message: '请选择设备信息', duration: 2000 })
      } else {
        MessageBox.confirm('当前选中' + this.selectList.length + '条信息，是否删除?', {
          confirmButtonText: this.$t('common.confirm'), confirmButtonText: this.$t('common.cancel'), type: 'warning'
        }).then(() => {
          console.log(this.selectList)
          this.requestParam = {}
          this.requestParam.common = { 'returnmap': '0' }
          this.requestParam.data = []
          this.requestParam.data[0] = { 'name': 'insertSpotList', 'resultmaps': { 'list': this.selectList }}
          this.requestParam.data[0].children = []
          this.requestParam.data[0].children[0] = { 'name': 'deleteTmrEquipment', 'type': 'e', 'parammaps': {
            id: '@insertSpotList.id'
          }}
          ExecDataByConfig(this.requestParam).then(response => {
            console.log('删除保存发送参数', this.requestParam)
            if (response.msg === 'fail') {
              this.$notify({ title: this.$t('common.delfail'), message: response.data, type: 'warning', duration: 2000 })
            } else {
              this.$notify({ title: '',message: this.$t('common.delSuccess'), type: 'success', duration: 2000 })
              this.getList()
            }
          })
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
  .search{margin-top:10px;}

</style>
