<script>
import {copy, fuzzyMatching, splitKeyWords} from "@/utils/common.js";
import {Delete, Document, DocumentAdd, Edit, Search, Tickets} from "@element-plus/icons-vue";
import ZooAnimalFormDialog from "@/components/ZooAnimalFormDialog.vue";
import {mapActions, mapMutations, mapState} from "vuex";
import ZooArchiveTimeline from "@/components/ZooArchiveTimeline.vue";

export default {
  name: "ZooAnimal",
  components: {ZooArchiveTimeline, ZooAnimalFormDialog},
  data() {
    return {
      //表格分页显示的数据
      pagesData: [],
      pageSize: 20,//每页有多少条数据
      currentPage: 1,//当前页

      // 搜索框的输入
      searchInput: {
        option: '',//状态（0正常 1异常）
        keyword: ''
      },

      // 控制弹窗的属性
      dialog: {
        dialogData: {},//弹窗数据
        addDialogVisible: false,//添加对话框
        editDialogVisible: false,//编辑对话框
        detailDialogVisible: false,//详情对话框
        timelineDialogVisible:false,//时间线对话框
        timelineData:[]//时间线数据
      }
    }
  },
  computed: {
    //图标
    //region
    Search() {
      return Search
    },
    Document() {
      return Document
    },
    Edit() {
      return Edit
    },
    Delete() {
      return Delete
    },
    DocumentAdd() {
      return DocumentAdd
    },
    Tickets() {
      return Tickets
    },
    //endregion
    ...mapState(["animals",'archives','animalsTableData'])
  },
  watch: {
    // 搜索框存在输入，自动调用搜索
    searchInput: {
      deep: true,
      handler(val) {
        this.search();
      }
    }
  },
  methods: {
    ...mapActions(["getAnimals"]),
    ...mapMutations(['updateAnimalsTableData']),

    // 显示详情弹窗
    showDetail(data) {
      console.log('显示详情', data)

      //从后端获取需要查询的数据，防止数据前后不一致
      //这里先用假数据代替一下
      this.dialog.dialogData = this.animals.find(e => e.id === data.id)

      //显示弹窗
      this.dialog.detailDialogVisible = true
    },

    //显示编辑弹窗
    showEdit(data) {
      console.log('显示编辑', data)

      //从后端获取需要查询的数据，防止数据前后不一致
      //这里先用假数据代替一下
      this.dialog.dialogData = this.animals.find(e => e.id === data.id)

      //显示弹窗
      this.dialog.editDialogVisible = true
    },

    edit(data) {
      console.log('编辑', data)

      //判断表单是否为空
      return this.isEmpty(data);

      //这里将数据传给后端进行数据更新
      //编辑失败
      if (false) {
        return ElMessage({
          message: '编辑失败',
          type: 'warning',
        })
      }

      //编辑成功
      if (false) {
        return ElMessage({
          message: '编辑成功',
          type: 'success',
        })
      }

      //从后端重新拉取数据
      this.getAnimals()

      //关闭窗口
      this.dialog.editDialogVisible = false
    },

    delete_(data) {
      console.log('删除', data)

      return ElMessageBox.confirm(
          '该操作不可撤销，是否继续？',
          '删除动物：' + data.name + '（'+data.id+'）',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
      ).then(() => {
        //进行删除操作

        //重新拉取数据
        this.getAnimals()

        // 返回提示
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      }).catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
    },

    add(data) {
      console.log('添加', data)

      //验证是否为空
      return this.isEmpty(data);

      //先查询用户是否存在

      //添加失败
      if (false) {
        return ElMessage({
          message: '该动物已存在',
          type: 'warning',
        })
      }
      //添加成功
      if (false) {
        return ElMessage({
          message: '添加成功',
          type: 'success',
        })
      }
      // 此处重新拉取数据
      this.getAnimals()
      this.dialog.addDialogVisible = false//添加成功关闭窗口
    },

    //以时间线的形式查看该动物的所有档案记录
    showArchives(data) {
      console.log('显示档案', data)

      //从后端获取需要查询的数据，防止数据前后不一致
      //这里先用假数据代替一下
      this.dialog.dialogData = this.animals.find(e => e.id === data.id)

      this.dialog.timelineData = []
      //从后端获取需要查询的数据，防止数据前后不一致
      //这里先用假数据代替一下
      this.archives.forEach(e=>{
        if (e.animalId === data.id) {
          this.dialog.timelineData.push(e)
        }
      })

      //显示弹窗
      this.dialog.timelineDialogVisible = true
    },

    // 判断表单是否为空
    isEmpty(form) {
      if (!form.name) {
        //返回提示
        return ElMessage({
          message: '动物名不能为空',
          type: 'warning',
        })
      }
    },

    search() {
      console.log('搜索', this.searchInput)

      let searchResult = []//搜索结果数组

      //第一步匹配搜索选项
      if (typeof this.searchInput.option === 'number') {
        this.animals.forEach(e => {
          if (e.state === this.searchInput.option) {
            searchResult.push(copy(e))//如果符合特定权限，则添加到搜索结果
          }
        })
      } else { //如果没有选择特定用户身份，代表所有数据都需要参加到下一轮的模糊搜索
        searchResult = copy(this.animals)
      }

      let searchResult2 = []
      let keyset = splitKeyWords(this.searchInput.keyword)//切割关键字

      //第二步进行模糊搜索
      searchResult.forEach(e => {
        //如果该对象能匹配上所有关键字，则添加到结果
        // console.log('开始进行模糊匹配,对象、关键字集合分别为',e,keyset)
        let is = fuzzyMatching(e, keyset);
        if (is) {
          searchResult2.push(e)
        }
        // console.log('结束模糊匹配，结果为',e,keyset,is)
      })
      searchResult = searchResult2

      this.updateAnimalsTableData(searchResult)
      this.getPagesData()
    },

    //当前页切换时触发
    handleCurrentChange(val) {
      console.log('分页被切换',val)
      this.currentPage = val
      this.getPagesData()
    },

    getPagesData() {
      console.log('获取分页数据')
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      this.pagesData = this.animalsTableData.slice(start, end)
    }
  },
  mounted() {
    // 加载完成后拉取数据
    this.getAnimals()

    //获取分页后显示的数据
    this.getPagesData()
  }
}
</script>

<template>
  <div class="animals-root">
    <div class="select">
      <div class="left">
        <el-button type="primary" :icon="DocumentAdd" @click="dialog.addDialogVisible = true">添加动物</el-button>
      </div>
      <div class="right">
        <el-input
            v-model="searchInput.keyword"
            style="width: 500px"
            placeholder="搜索动物 空格隔开关键字"
        >
          <template #prepend>
            <el-select v-model="searchInput.option" placeholder="状态" style="width: 80px">
              <el-option label="不选择" value=""/>
              <el-option label="正常" :value="0"/>
              <el-option label="异常" :value="1"/>
            </el-select>
          </template>
          <template #append>
            <el-button :icon="Search" @click="search()"/>
          </template>
        </el-input>
      </div>
    </div>

    <!--    <hr/>-->
    <div class="table">
      <el-table :data="pagesData" style="width: 100%;height: 100%" border stripe :row-style="{height: '40px'}" :cell-style="{padding:'0'}">
        <el-table-column fixed prop="id" label="动物ID" width="70"/>
        <el-table-column fixed prop="name" label="动物名称" width="100"/>
        <el-table-column prop="sex" label="性别" width="60"/>
        <el-table-column prop="species" label="动物种类" width="90"/>
        <el-table-column prop="weight" label="动物体重（KG）" width="130"/>
        <el-table-column prop="height" label="动物身高（M）" width="130"/>
        <el-table-column prop="state" label="动物状态" width="90">
          <template #default="scope">
            <span v-if="scope.row.state===0" style="color: green">正常</span>
            <span v-else-if="scope.row.state===1" style="color: red">异常</span>
            <span v-else>未知</span>
          </template>
        </el-table-column>
        <el-table-column prop="phase" label="生命阶段" width="90"/>
        <el-table-column prop="roleId" label="饲养员ID" width="120"/>
        <el-table-column prop="color" label="动物颜色" width="150">
          <template #default="scope">
            {{ scope.row.color }}
            <el-color-picker v-model="scope.row.color" disabled/>
          </template>
        </el-table-column>
        <el-table-column prop="features" label="动物特征" width="200"/>
        <el-table-column fixed="right" label="操作" width="250">
          <template #default="scope">
            <el-button link type="success" size="small" :icon="Tickets" @click="showArchives(scope.row)">
              档案
            </el-button>
            <el-button link type="primary" size="small" :icon="Document" @click="showDetail(scope.row)">
              详情
            </el-button>
            <el-button link type="primary" size="small" :icon="Edit" @click="showEdit(scope.row)">
              编辑
            </el-button>
            <el-button link type="danger" size="small" :icon="Delete" @click="delete_(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!--  分页-->
    <div class="pager relative">
      <div class="center">
        <el-pagination background layout="total, prev, pager, next, jumper" :total="animalsTableData.length"
                       :page-size="pageSize" small @current-change="handleCurrentChange"/>
      </div>
    </div>
  </div>

  <!--  添加动物对话框-->
  <el-dialog v-model="dialog.addDialogVisible" title="添加动物" width="500" align-center draggable overflow>
    <ZooAnimalFormDialog>
      <template #default="scope">
        <el-button @click="dialog.addDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="add(scope.form)">
          添加
        </el-button>
      </template>
    </ZooAnimalFormDialog>
  </el-dialog>

  <!--  编辑动物对话框-->
  <el-dialog v-model="dialog.editDialogVisible" title="编辑动物" width="500" align-center draggable overflow
             destroy-on-close>
    <ZooAnimalFormDialog :data="dialog.dialogData" edit>
      <template #default="scope">
        <el-button @click="dialog.editDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="edit(scope.form)">
          修改
        </el-button>
      </template>
    </ZooAnimalFormDialog>
  </el-dialog>

  <!--  查看动物对话框-->
  <el-dialog v-model="dialog.detailDialogVisible" title="查询动物" width="500" align-center draggable overflow
             destroy-on-close>
    <ZooAnimalFormDialog :data="dialog.dialogData" detail>
      <template #default="scope">
        <el-button @click="dialog.detailDialogVisible = false">
          关闭
        </el-button>
      </template>
    </ZooAnimalFormDialog>
  </el-dialog>

  <!--查看动物所有记录-->
  <el-dialog v-model="dialog.timelineDialogVisible" :title="'动物档案：'+dialog.dialogData.id" width="600" align-center draggable overflow
             destroy-on-close>
    <ZooArchiveTimeline :data="dialog.timelineData">
<!--      <template #operate="scope">-->
<!--        <el-button type="primary" link @click="showEdit(scope.archive)">编辑</el-button>-->
<!--        <el-button type="danger" link @click="delete_(scope.archive)">删除</el-button>-->
<!--      </template>-->
      <template #footer>
        <el-button type="primary" @click="$router.push('/panel/archive')">
          跳转至动物档案
        </el-button>
        <el-button @click="dialog.timelineDialogVisible = false">
          关闭
        </el-button>
      </template>
    </ZooArchiveTimeline>
  </el-dialog>
</template>

<style scoped>
/*.table {*/
/*  !*width: 1300px;*!*/
/*  height: 546px;*/
/*  margin: 0 30px;*/
/*}*/

/*.left {*/
/*  margin-left: 30px;*/
/*}*/

/*.right {*/
/*  margin-right: 30px;*/
/*}*/


/*.select {*/
/*  width: 100%;*/
/*  height: 60px;*/
/*  line-height: 60px;*/
/*}*/
</style>