<template>
  <div class="app-container">
    <div class="search">
      <el-select v-model="table.parammaps.parent_id" filterable placeholder="牲畜父类" class="filter-item"
        style="width: 160px;" clearable>
        <el-option v-for="item in parentList" :key="item.value" :label="item.label" :value="item.label" />
      </el-select>
      <el-input v-model="table.parammaps.name" placeholder="牲畜类别" style="width: 180px;" class="filter-item" clearable />
      <el-select v-model="table.parammaps.is_show" placeholder="是否启用" class="filter-item" style="width: 120px;"
        clearable>
        <el-option v-for="item in enableList" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button class="successBorder" @click="handleSearch">查询</el-button>
      <el-button class="successBorder" @click="handleRefresh">重置</el-button>
    </div>
    <div class="operation">
      <el-button class="success" v-if="isAdd" icon="el-icon-plus" @click="handleCreate">新增</el-button>
      <el-button class="danger" v-if="isDelete" icon="el-icon-delete" @click="handleDelete">删除</el-button>
    </div>
    <div class="table">
      <el-table :key="table.tableKey" v-loading="table.listLoading" element-loading-text="给我一点时间" :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="序号" min-width="130px" align="center" prop="id" />
        <el-table-column label="牲畜父类" min-width="200px" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.NoEdit">{{ scope.row.parent_name }}</span>
            <el-select v-if="scope.row.Edit" v-model="scope.row.parent_id" filterable placeholder="牲畜类别父类"
              class="filter-item" style="width:95%;padding:10px 0;" @change="changeParent">
              <el-option v-for="item in parentList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="牲畜类别" min-width="200px" 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:95%;padding:0 10px;" maxlength="32" />
          </template>
        </el-table-column>
        <el-table-column label="牲畜类别编号" min-width="200px" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.NoEdit">{{ scope.row.number }}</span>
            <el-input v-if="scope.row.Edit" v-model="scope.row.number" placeholder="1-32个字符" type="textarea"
              :autosize="{ minRows: 1.3, maxRows: 4}" maxlength="32" style="width:95%;padding:0 10px;" />
          </template>
        </el-table-column>
        <el-table-column label="来源" min-width="200px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.data_source }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否启用" min-width="110px" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.is_show"active-color="#13ce66" :disabled="!isEnable"
              inactive-color="#ff4949" :active-value="1" :inactive-value="2"
              @change="handleEnableChange(scope.$index, scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="80" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="{row}">
            <!-- 新增 -->
            <el-button v-if="row.isCreate && isAdd" :disabled="isokDisable" icon="el-icon-folder-checked" class="miniSuccess"
              @click="createData(row)" />
            <span v-if="row.isCreate && isAdd" class="centerSpan">|</span>
            <el-button v-if="row.isCreate && isAdd" class="minCancel" icon="el-icon-close" @click="createCancel(row)" />
            <!-- 编辑 -->
            <el-button v-if="row.isUpdate && isEdit" class="miniSuccess" icon="el-icon-edit-outline" @click="handleUpdate(row)" />
            <span v-if="row.isUpdate && isDelete" class="centerSpan">|</span>
            <el-button v-if="row.isUpdate && isDelete" class="miniDanger" icon="el-icon-delete" @click="handleRowDelete(row)" />
            <!-- 编辑保存 -->
            <el-button v-if="row.isUpdateSave && isEdit" :disabled="isokDisable" icon="el-icon-folder-checked" class="miniSuccess"
              @click="updateData(row)" />
            <span v-if="row.isUpdateSave && isEdit" class="centerSpan">|</span>
            <el-button v-if="row.isUpdateSave && isEdit" class="minCancel" icon="el-icon-close" @click="updateCancel(row)" />
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="table.total>=0" :total="table.total" :page.sync="table.page" :limit.sync="table.page_size"
        @pagination="getList" />
    </div>
  </div>

</template>

<script>
  import { postJson,delJson,checkButtons } from '@/api/common'
  import Cookies from 'js-cookie'
  import Pagination from '@/components/Pagination'
  import { MessageBox } from 'element-ui'
  export default {
    name: 'LivestockCategory',
    components: {
      Pagination
    },
    data() {
      return {
        table: {
          page: 1,
          page_size: parseInt(Cookies.get('pageCount')),
          tableKey: 0,
          list: [],
          total: 0,
          listLoading: true,
          parammaps: {
            name: '',
            manager_user: '',
            manager_phone: '',
            is_show: '',
            inputDatetime: [],
            end_time: '',
            start_time: ''
          },
          temp:{}
        },
        enableList: JSON.parse(sessionStorage.downlist).is_show,
        parentList: JSON.parse(sessionStorage.downlist).cattle_parent_category,

        isokDisable: false,
        selectList: [],
        isAdd:'',isEdit:'',isDelete:'',isEnable:'',
        rowStyle: {
          maxHeight: 30 + 'px',
          height: 30 + 'px'
        },
        cellStyle: {
          padding: 0 + 'px'
        }

      }
    },

    created() {
      this.getButton()
      this.getList()
    },

    methods: {
      getButton(){
        const add = 'rangeManagement:livestockCategory:add'
        this.isAdd = checkButtons(add)
        const edit = 'rangeManagement:livestockCategory:edit'
        this.isEdit = checkButtons(edit)
        const del = 'rangeManagement:livestockCategory:delete'
        this.isDelete = checkButtons(del)
        const enable = 'rangeManagement:livestockCategory:enable'
        this.isEnable = checkButtons(enable)
      },
      getList() {
        this.table.listLoading = true
        let page = this.table.page
        let page_size = this.table.page_size
        let url = 'api/v1/ops/cattle/category/list' + '?page=' + page + '&page_size=' + page_size
        let data = {
          "name": this.table.parammaps.name
        }
        if (this.table.parammaps.parent_id !== '') {
          data.parent_id = this.table.parammaps.parent_id
        }
        if (this.table.parammaps.is_show !== '') {
          data.is_show = this.table.parammaps.is_show
        }
        postJson(url, data).then(response => {
          console.log('table数据', response.data.list)
          if (response.data.list !== null) {
            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.total = response.data.total
            this.table.pageNum = response.data.page
            this.table.pageSize = response.data.page_size
          } else {
            this.table.list = []
          }
          setTimeout(() => {
            this.table.listLoading = false
          }, 100)
        })
      },
      handleEnableChange(index, row) {
       let url = 'api/v1/ops/cattle/category/is_show'
       let data = {
         "cattle_category_id":row.id,
         "is_show":row.is_show
       }
       postJson(url,data).then(response => {
         if(response.code == 200){
           this.$notify({ title: '成功', message: '成功', type: 'success', duration: 2000 })
           this.getList()
         }
       })
      },
      handleSearch() {
        console.log('点击了查询')
        this.table.page = 1
        this.getList()
      },
      handleRefresh() {
        console.log('点击了重置')
        this.table.parammaps.name = ''
        this.table.parammaps.parent_id = ''
        this.table.parammaps.is_show = ''
        this.table.page = 1
        this.getList()
      },

      changeParent(val) {
        console.log('点击了牲畜类别父类', val)
        console.log(this.parentList.find(obj => obj.value == val).label)
        this.table.temp.parent_id = val
        this.table.temp.parent_name = this.parentList.find(obj => obj.value == val).label
        console.log( this.table.temp)
        this.$forceUpdate()
      },
      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: '当前内容未保存，请点击取消或保存继续进行操作',
              duration: 2000
            })
            return false
          }
        }
        this.table.list.unshift({
          'myId': (new Date()).valueOf(),
          'Edit': true,
          'NoEdit': false,
          'isCreate': true,
          'isUpdate': false,
          'isUpdateSave': false,
          'parent_id': '',
          'parent_name': '',
          'name':'',
          'number':'',
          'is_show': 1,
        })
      },
      createData(row) {
        this.table.temp.parent_id = row.parent_id
        this.table.temp.name = row.name
        this.table.temp.number = row.number
        this.table.temp.is_show = row.is_show
        // 牲畜父类/牲畜类别/牲畜类别编号是否为空
        if (this.table.temp.parent_id == '' && this.table.temp.name == '' && this.table.temp.number == '') {
          this.$message({ type: 'error', message: '牲畜父类/牲畜类别/牲畜类别编号不能为空', duration: 2000 })
          return false
        } else if (this.table.temp.parent_name == '' && this.table.temp.number == '') {
          this.$message({ type: 'error', message: '牲畜类别/牲畜类别编号不能为空', duration: 2000 })
          return false
        } else if (this.table.temp.parent_id == '') {
          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.number == '') {
          this.$message({ type: 'error', message: '牲畜类别编号不能为空', duration: 2000 })
          return false
        }
        const pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]")
        if (pattern.test(this.table.temp.number)) {
          this.$message({ type: 'error', message: '牲畜类别不可输入特殊字符', duration: 2000 })
          return false
        }
        if (pattern.test(this.table.temp.number)) {
          this.$message({ type: 'error', message: '牲畜类别编号不可输入特殊字符', duration: 2000 })
          return false
        }
        let url = 'api/v1/ops/cattle/category/add'
        let data = {
          'parent_id': this.table.temp.parent_id,
          "parent_name": this.table.temp.parent_name,
          "name": this.table.temp.name,
          "number": this.table.temp.number,
          "is_show": this.table.temp.is_show
        }
        postJson(url, data).then(response => {
          if (response.code == 200) {
            this.$notify({
              title: '',
              message: '成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }
        })
      },
      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) {
        console.log('点击了编辑', 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
          }
        }
        // 编辑true,不可编辑false
        row.Edit = true
        row.NoEdit = false
        // 新增false,编辑false,编辑保存true
        row.isCreate = false
        row.isUpdate = false
        row.isUpdateSave = true
        if (row.parent_id == undefined) {
          this.$set(row, 'parent_id', '')
          this.$set(row, 'parent_name', '')
          this.$set(this.table.temp, 'parent_id', '')
          this.$set(this.table.temp, 'parent_name', '')
        }
        this.table.temp.parent_id = row.parent_id
        this.table.temp.parent_name = row.parent_name
        this.table.temp.name = row.name
        this.table.temp.number = row.number
        this.table.temp.is_show = row.is_show
      },
      updateData(row) {
        this.table.temp.parent_id = row.parent_id
        this.table.temp.name = row.name
        this.table.temp.number = row.number
        this.table.temp.is_show = row.is_show
        this.table.temp.id = row.id
        // 牲畜父类/牲畜类别/牲畜类别编号是否为空
        if (this.table.temp.parent_id == '' && this.table.temp.name == '' && this.table.temp.number == '') {
          this.$message({ type: 'error', message: '牲畜父类/牲畜类别/牲畜类别编号不能为空', duration: 2000 })
          return false
        } else if (this.table.temp.parent_name == '' && this.table.temp.number == '') {
          this.$message({ type: 'error', message: '牲畜类别/牲畜类别编号不能为空', duration: 2000 })
          return false
        } else if (this.table.temp.parent_id == '') {
          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.number == '') {
          this.$message({ type: 'error', message: '牲畜类别编号不能为空', duration: 2000 })
          return false
        }
        const pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]")
        if (pattern.test(this.table.temp.number)) {
          this.$message({ type: 'error', message: '牲畜类别不可输入特殊字符', duration: 2000 })
          return false
        }
        if (pattern.test(this.table.temp.number)) {
          this.$message({ type: 'error', message: '牲畜类别编号不可输入特殊字符', duration: 2000 })
          return false
        }
        let url = 'api/v1/ops/cattle/category/edit'
        let data = {
          'parent_id': this.table.temp.parent_id,
          "parent_name": this.table.temp.parent_name,
          "name": this.table.temp.name,
          "number": this.table.temp.number,
          "is_show": this.table.temp.is_show,
          "id":this.table.temp.id
        }
        console.log(data)
        postJson(url, data).then(response => {
          if (response.code == 200) {
            this.$notify({
              title: '',
              message: '成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }
        })

      },
      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('是否确认删除此信息?', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.selectList = []
          let url = 'api/v1/ops/cattle/category/'
          let data = row.id
          delJson(url, data).then(response => {
            if (response.code == 200) {
              this.$notify({
                title: '',
                message: '成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            }
          })
        })
      },
      handleSelectionChange(val) {
        console.log('勾选数据', val)
        this.selectList = val
      },
      handleDelete() {
        console.log('点击了删除')
        if (this.selectList.length == 0) {
          this.$message({
            type: 'error',
            message: '请选择牲畜类别信息',
            duration: 2000
          })
        } else {
          MessageBox.confirm('当前选中' + this.selectList.length + '条信息，是否删除?', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {

          })
        }
      }
    }
  }
</script>
<style lang="scss" scoped>
  .search {
    margin-top: 10px;
  }
</style>
