<template>
 
  <div>


    <el-card class="box-card">
      <!-- 搜索区域 -->
      <div class="search-bx1">
          <el-input v-model="searchData.name" placeholder="栏舍名称"  style="width: 180px;" class="g-mr20" clearable />
          <el-input v-model="searchData.barn_group_name" placeholder="栏舍组"  style="width: 180px;" class="g-mr20" clearable />
          <el-input v-model="searchData.number" placeholder="身份卡ID"  style="width: 180px;" class="g-mr20" clearable />
          <el-select v-model="searchData.status" filterable placeholder="栏舍状态" class="g-mr20" style="width: 180px;" clearable>
            <el-option v-for="item in statusList" :key="item.id" :label="item.value" :value="item.id" />
          </el-select>
          <!-- <el-select v-model="searchData.barn_group_id" filterable placeholder="犊牛状态" class="g-mr20" style="width: 180px;" clearable>
            <el-option v-for="item in barnGroupList" :key="item.id" :label="item.value" :value="item.id" />
          </el-select> -->
          <el-button type="primary"   @click="form_search">搜索</el-button>
          <el-button type="primary"   @click="form_clear">重置</el-button>
          <el-button   type="primary"   @click="tab_view">切换视图</el-button>
          <el-button type="primary"  v-if="isButtonEdit"  @click="form_add">添加</el-button>
           <!-- <el-button type="primary"   @click="form_export">导出</el-button> -->
      </div>

 

      <div   v-if = "tabView == 'table'">
        <!-- 表格 -->
        <el-table   key="0"  :data="tableList"  v-loading="tableLoading" element-loading-text="给我一点时间"    border fit>
          <el-table-column label="序号"  width="50px" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.id }}</span>
            </template>
          </el-table-column>
          <el-table-column label="栏舍名称" min-width="150px" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="栏舍组" min-width="150px" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.barn_group_name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="身份卡ID" min-width="150px" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.number }}</span>
            </template>
          </el-table-column>
          <el-table-column label="栏舍状态" min-width="150px" align="center">
            <template slot-scope="scope">
              <span v-if ="scope.row.status == 1">正常</span>
              <span v-if ="scope.row.status == 2">疾病</span>
              <span v-if ="scope.row.status == 3">断奶</span>
              <span v-if ="scope.row.status == 4">空栏</span>
  
            </template>
          </el-table-column>
    
          <el-table-column label="犊牛状态" min-width="150px" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.calf_status == 0">未知</span>
              <span v-if="scope.row.calf_status == 1">健康</span>
              <span v-if="scope.row.calf_status == 2">生病</span>
     

       
            </template>
          </el-table-column>
  

          <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width" fixed="right">
            <template slot-scope="scope">
              <!-- 修改按钮 -->
              <el-button type="primary" v-if="isButtonEdit"  size="mini" icon="el-icon-edit" @click="form_edit(scope.row)">修改</el-button>
              <!-- 删除按钮 -->
              <el-button type="danger" v-if="isButtonEdit"  size="mini" icon="el-icon-delete" @click="form_delete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <el-pagination  @size-change="change_size_page"  @current-change="change_current_page"  :current-page="searchData.page" :page-sizes="[1,5,10,20,30,50]"  :page-size="searchData.page_size" layout="total, prev, pager, next" :total="searchData.total"/>
      </div>
      <div   v-if = "tabView == 'view'"  >
        <el-row :gutter="20">
          
          <el-col :span="12">
            <div>
              <el-row :gutter="10" style = "margin-bottom:20px; margin-top:40px;">
    
                <el-col :span="4" :offset="4">
                  <span class = "column-item column-color1"  ></span>
                  <span class = "column-txt">正常</span>
                </el-col>
                <el-col :span="4">
                  <span class = "column-item column-color2"  ></span>
                  <span class = "column-txt">发病</span>
                </el-col>
                <el-col :span="4">
                  <span class = "column-item column-color3"  ></span>
                  <span class = "column-txt">断奶</span>
                </el-col>
                <el-col :span="4">
                  <span class = "column-item column-color4"  ></span>
                  <span class = "column-txt">空栏</span>
                </el-col>
              </el-row>
            </div>
            <div v-for="item in columnViewList" :key="index">
              <el-row :gutter="10">
                <el-col :span="4">{{item.barn_group_name}}</el-col>
                <el-col :span="20">
                  <!-- 数量不定的栏舍 -->
                  <el-col :span="3" v-for="items in item.barn_view" :key="index">

                    <div style = "margin-bottom:20px;text-align:center">

                      <i class="el-icon-house  column-color11" style = "font-size:34px" v-if="items.barn_status == 1"></i>
                      <i class="el-icon-house  column-color22" style = "font-size:34px" v-if="items.barn_status == 2"></i>
                      <i class="el-icon-house  column-color33" style = "font-size:34px" v-if="items.barn_status == 3"></i>
                      <i class="el-icon-house  column-color44" style = "font-size:34px" v-if="items.barn_status == 4"></i>
                     
                      <!-- <span class = "column-item column-color1" v-if="items.barn_status == 1"></span>
                      <span class = "column-item column-color2" v-if="items.barn_status == 2"></span>
                      <span class = "column-item column-color3" v-if="items.barn_status == 3"></span>
                      <span class = "column-item column-color4" v-if="items.barn_status == 4"></span> -->
                      <span class = "column-txt">{{items.barn_name}}</span>
                    </div>
                  </el-col>
                </el-col>
              </el-row>
            </div>
            
  
          </el-col>
          <el-col :span="12">
              <!-- 图表 -->
            <div id="chartPie1"  style="width: 100%;height:400px;"></div>  
          </el-col>
        </el-row>
        
      </div>
    </el-card>


    


    <!-- 弹窗 新增or修改 -->
    <el-dialog  :title="addFormTxt[addFormStatus]" :visible.sync="addFormShow" @close="add_dialog_close" width="50%">
      <div class="">
        <el-form  ref="addFormRef"  :rules="addFormRules"  :model="addForm"  label-position="right" label-width="100px"  style="width:50%;margin:0 auto 50px">
            <el-form-item label="身份卡ID：" prop="number">
                <el-input   v-model="addForm.number"  placeholder="用于加奶枪识别牛只信息及饲喂量"  ></el-input>  
            </el-form-item>
            <el-form-item label="栏舍名称：" prop="name">
                <el-input   v-model="addForm.name"    ></el-input>  
            </el-form-item>       
            <el-form-item label="栏舍组：" prop="barn_group_id">
              <el-select  v-model="addForm.barn_group_id" filterable placeholder="请选择" class="filter-item" style="width: 100%;" >
                <el-option v-for="item in barnGroupList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item> 
           
            
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addFormStatus==='create'?add_dialog_save():edit_dialog_save()">确认</el-button>
          <el-button @click="addFormShow = false">关闭</el-button>
        </div>
      </div>
    </el-dialog>

 
    
  </div>


</template> 

<script>
import {  ajaxDataGet, ajaxDataPost, ajaxDataPut, ajaxDataDelete, checkButtons} from '@/api/common'
import { parseTime, json2excel } from '@/utils/index.js'
import * as echarts from 'echarts';
export default {
  data() {


    
 
  
    return {

 

      //接口 - 获取 - 表格
      url_get_table:'/api/v1/ops/barn/list',
      //接口 - 新增 - 表格
      url_add_table:'/api/v1/ops/barn/add',  
      //接口 - 修改 - 表格
      url_edit_table:'/api/v1/ops/barn/update', 
      //接口 - 删除 - 表格
      url_delete_table:'/api/v1/ops/barn/delete', 
      
      //接口 - 下拉框 列表 
      url_get_select1:'/api/v1/ops/calf_feed/enum/list',

      //接口 - 下拉框 列表 栏舍组
      url_get_select2:'/api/v1/ops/barn_group/list?page=1&page_size=1000',

      //按钮权限
      isButtonEdit:false,


      //切换视图模式， table 表格，view 图
      tabView:'table',


      //视图模式中的栏舍
      columnViewList:[
        // {
        //   barn_group_name:"A001",
        //   barn_view:[
        //       { barn_id: '1', barn_name: '001', status: '正常'  },
        //       { barn_id: '1', barn_name: '002', status: '发病'  },
        //   ]
        // },
        // {
        //   barn_group_name:"A002",
        //   barn_view:[
        //       { barn_id: '1', barn_name: '001', status: '正常'  },
        //       { barn_id: '1', barn_name: '002', status: '发病'  },
        //   ]
        // },
         
      ],

      //获取 - 表格数据 - 参数
      searchData:{
        name: "",
        barn_group_name: "",
        number: "",
        status: undefined,
        page: 1,  //页码
        page_size: 10,   //每页数量
        total:0,  //总页数
        pastureId: ""
      },
      tableLoading: false,
      //表格内容
      tableList:[
        //  { username:"admin", id:100, date:'2023-12-01',email:'测试信息1123',roleList:[2,3] },
        // { username:"epans", id:200, date:'2023-12-01',email:'测试信息1123',roleList:[] },
        // { username:"derek", id:300, date:'2023-12-01',email:'测试信息1123' },
        // { username:"admin", id:100, date:'2023-12-01',email:'测试信息1123' },
        // { username:"epans", id:200, date:'2023-12-01',email:'测试信息1123' },
        // { username:"derek", id:300, date:'2023-12-01',email:'测试信息1123' },
        // { username:"admin", id:100, date:'2023-12-01',email:'测试信息1123' },
        // { username:"epans", id:200, date:'2023-12-01',email:'测试信息1123' },
        // { username:"derek", id:300, date:'2023-12-01',email:'测试信息1123' },
        // { username:"admin", id:100, date:'2023-12-01',email:'测试信息1123' },
        // { username:"epans", id:200, date:'2023-12-01',email:'测试信息1123' },
        // { username:"derek", id:300, date:'2023-12-01',email:'测试信息1123' },
      ],


      //栏舍状态
      statusList:[
        {id: 1, value: '正常'},
        {id: 2, value: '疾病'},
        {id: 3, value: '断奶'},
        {id: 4, value: '空栏'},
      ],

     //图表实例
     chartPie1: null,
      //图表数据
      chartPie1_data: {  num1:5.26,num2:0,num3:5.26,num4:89.48 },

      //栏舍组下拉
      barnGroupList:[
         
      ],


      addFormShow:false,
      addFormStatus: '',
      addFormTxt: {  edit: '修改',  create: '新增' },
      addForm:{
        number:undefined,name:'',barn_group_id:undefined,id:'' 
      },

      addFormRules:{
        number: [ { required: true, message: '身份卡ID必填', trigger: 'blur' },  ],
        name: [ { required: true, message: '类型名称必填', trigger: 'blur' },  ],
        barn_group_id: [ { required: true, message: '栏舍组必填', trigger: 'blur' },  ],

      },

     
       
    }
  },
  created(){
      //获取按钮权限
      const isButtonEdit = checkButtons(this.$store.state.buttonsList, "牛只栏舍编辑")
      this.isButtonEdit = isButtonEdit
      console.log('this.isButtonEdit==========',this.isButtonEdit)
     

     //获取下拉框
     this.get_select_list1()

      //表格 - 初始化 
      this.get_table_data()
      this.get_chart()

     

    
  },
  methods:{

  
    
    //获取 下拉框
    get_select_list1(){
        var me = this
        ajaxDataPost(me.url_get_select2, { name: ""}).then(e => {
          console.log("栏舍组下拉框：",e)

          if(e.data.list == null || e.data.list == undefined ||e.data.list.length == 0   ){
            me.barnGroupList = []
          } else {
            me.barnGroupList = e.data.list
          }

         
  
        })


        // ajaxDataGet('/authdata/pasture', {  "page": 1,   "page_size": 1000}).then(e => {
        //   console.log("牧场下拉框1：",e)

        //   //打印请求成功结果
        //   if(e.data == null || e.data == undefined ||e.data.length == 0   ){
        //     me.pastureList = []
        //   } else {
        //     me.pastureList = e.data
        //   }
  
        // })

    
    },

    //获取 图表
    get_chart(){
      var me = this
        
      ajaxDataPost('/api/v1/ops/barn/view', me.searchData).then(e => {
          console.log("获取视图：",e)

          //获取栏舍视图块块+饼图
          if(e.data == null || e.data == undefined   ){
            me.columnViewList = []
            me.chartPie1_data.num1 = 0
            me.chartPie1_data.num2 = 0
            me.chartPie1_data.num3 = 0
            me.chartPie1_data.num4 = 0

          } else {
            me.columnViewList = e.data.barn_group_view
            me.chartPie1_data.num1 = e.data.disease_number
            me.chartPie1_data.num2 = e.data.weaning_reminders_number
            me.chartPie1_data.num3 = e.data.void_number
            me.chartPie1_data.num4 = e.data.normalcy_number

          }


   

  
        })

    },
    
    //获取 表格
    get_table_data() {
 
     var me = this

     me.tableLoading = true
     console.log("searchData======>", me.searchData)


     
     if( me.searchData.status == ""){
        me.searchData.status = undefined
      }

      var send_url = me.url_get_table + '?page=' + me.searchData.page +  '&page_size=' + me.searchData.page_size

      ajaxDataPost(send_url,  me.searchData).then(e => {
        console.log("表格请求结果：",e)
          //打印请求成功结果
          if(e.code == 200 ){
            me.tableList = e.data.list
            me.searchData.total = e.data.total;	// 总数
            me.searchData.page = e.data.page;	//页码
            me.searchData.page_size = e.data.page_size;	//每页数量
           
          } else {
            me.$message({ type: 'error', message: '请求表格列表失败！' + e.msg, duration: 2000 })
          }

          setTimeout(() => {
            me.tableLoading = false
          }, 100)
  
        })

       
    },
    //搜索 查询表格
    form_search(){
      var me = this
      console.log('请求表格列表searchData',me.searchData)

      this.tabView = 'table'

      me.get_table_data()
      me.get_chart()

    },

    //重置 表格
    form_clear(){
      var me = this
      me.searchData.name = ""
      me.searchData.name = ""
      me.searchData.barn_group_name = undefined
      me.searchData.number = ""

   

      me.searchData.page = 1
      me.searchData.page_size = 10


      
      me.get_table_data()
    },

    //监听 page_size 改变的事件
    change_size_page(item){
      console.log(item)
     // this.searchData.page_size = item
      //  this.getUserList()
    },

    //监听 page 改变的事件
    change_current_page(item){
      console.log(item)
       this.searchData.page = item
       this.get_table_data()
    },

    //清空弹窗表单信息
    reset_form(){
      this.addForm.name = ''
      this.addForm.id = undefined
      this.addForm.barn_group_id = undefined
      this.addForm.number = ''
       
    },

    //新增
    form_add() {
      this.reset_form()
      this.addFormStatus = 'create'
      this.addFormShow = true
      this.$nextTick(() => {
        this.$refs['addFormRef'].clearValidate()
      })
    },

    //编辑
    form_edit(row) {
      this.reset_form()
      console.log('行内容row=========', row)
      //编辑行内容赋值
      this.addForm = Object.assign({}, row)  
      this.addFormStatus = 'edit'
      this.addFormShow = true
      this.$nextTick(() => {
        this.$refs['addFormRef'].clearValidate()
      })
    },


    //新增关闭
    add_dialog_close(){
       //内容重置
       this.$refs['addFormRef'].resetFields()
    },

    //新增 保存
    add_dialog_save() {
      var me = this
      this.$refs['addFormRef'].validate(valid => {
        //验证成功
        if (valid) {
          //发起请求
          var send_data = {
              "name": me.addForm.name,
              "barn_group_id": me.addForm.barn_group_id,
              "number": me.addForm.number,

          }
          console.log("弹窗参数：", send_data)

          //关闭弹窗
          // me.addFormShow = false
         //加载 - 发送新增保存
           ajaxDataPost(me.url_add_table, send_data).then(e => {
                console.log("新增结果：",e)
                //打印请求成功结果
                if(e.code == 200  ){
                  me.$message({ type: 'success', message: '新增成功！'  , duration: 2000 })
                  //关闭弹窗
                  me.addFormShow = false
                  me.get_table_data()
                } else {
                  me.$message({ type: 'error', message: '新增失败！' + e.msg, duration: 2000 })
                }
            })
         
        }
      })
    },
    //编辑 保存
    edit_dialog_save(){
      var me = this
      this.$refs['addFormRef'].validate(valid => {
        //验证成功
        if (valid) {
          //发起请求
          var send_data = {
    
              "id": me.addForm.id,
              "name": me.addForm.name,
              "barn_group_id": me.addForm.barn_group_id,
              "number": me.addForm.number,
          }

          // var name = this.barnGroupList.find(obj => obj.id == me.addForm.barn_group_id).name
          // console.log(name)

           // 编辑保存
          console.log("弹窗参数：", send_data)

          //关闭弹窗
          // me.addFormShow = false
         //加载 - 发送新增保存
         ajaxDataPut(me.url_edit_table, send_data).then(e => {
                console.log("编辑结果：",e)
                //打印请求成功结果
                if(e.code == 200  ){
                  me.$message({ type: 'success', message: '编辑成功！'  , duration: 2000 })
                  //关闭弹窗
                  me.addFormShow = false
                  me.get_table_data()
                } else {
                  me.$message({ type: 'error', message: '编辑失败！' + e.msg, duration: 2000 })
                }
            })
         
        }
      })
    },


    
    
    //监听 - 切换视图
    tab_view(){
      //切换视图模式，table表格，view图
      if(this.tabView == 'table'){
        this.tabView = 'view'
        setTimeout(() => {
          this.roadchartPie1()
        }, 500)
        
      } else {
        this.tabView = 'table'
      }

    },


    //图表数据加载
    roadchartPie1() {

      if (this.chartPie1 != null) {
        this.chartPie1.dispose()
      }
      this.chartPie1 = echarts.init(document.getElementById('chartPie1'))
      var option = {
        tooltip: {  trigger: 'item'  },
        series: [
          {
            name: '',
            type: 'pie',
            radius: [10, 100],
            center: ['50%', '50%'],
            
            itemStyle: {
              borderRadius: 8
            },
            label: {
              formatter: '{b|{b}：}  {per|{d}%}  ',
              backgroundColor: '#F6F8FC',
              borderColor: '#8C8D8E',
              borderWidth: 1,
              borderRadius: 4,
              lineHeight: 22,
              rich: {
                b: {
                  color: '#4C5058',
                  fontSize: 14,
                  fontWeight: 'bold',
                  lineHeight: 33
                },
                per: {
                  color: '#fff',
                  backgroundColor: '#4C5058',
                  padding: [3, 4],
                  borderRadius: 4
                }
              }
            },
            data: [
              //  { value: 300, name: '合同收入' },
              // { value: 200, name: '维修服务收入' },
              // { value: 200, name: '现场服务收入' },
              // { value: 20, name: '远程服务收入' }
              { value: this.chartPie1_data.num1, name: '发病' },
              { value: this.chartPie1_data.num2, name: '断奶提醒' },
              { value: this.chartPie1_data.num3, name: '空栏' },
              { value: this.chartPie1_data.num4, name: '正常' }
          
            ]
          }
        ]
      }


      this.chartPie1.setOption(option)
      window.onresize = function () {
        this.chartPie1.resize()
      }
    },


    form_delete(row) {
      var me = this

       me.$confirm('是否删除此条内容?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            console.log("删除的ID参数：", row.id)
            //加载 - 发送新增保存
            ajaxDataDelete(me.url_delete_table + '/' +row.id, {}).then(e => {
                console.log("编辑结果：",e)
                //打印请求成功结果
                if(e.code == 200  ){
                  me.$message({ type: 'success',  message: '删除成功!'  });
                  me.get_table_data()
                } else {
                  me.$message({ type: 'error', message: '删除失败！' + e.msg, duration: 2000 })
                }
            })

        
 
          
        }).catch(() => {
          me.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });


       
    },

 
    form_export() {
    //获取请求表格数据的参数
    //this.download.getdataListParm.parammaps = this.tableObj.getdataListParm.parammaps
    //请求表格
    // GetDataByName(this.download.getdataListParm).then(response => {
    //     if (response.data.list !== null) {
    //       this.download.list = response.data.list
    //     } else {
    //       this.download.list = []
    //     }
    //     var excelDatas = [
    //       {
    //         tHeader: ['表头1', '表头2', '表头3', '表头4',],
    //         filterVal: ['title1', 'title2', 'title3', 'title4'],
    //         tableDatas: this.download.list,
    //         sheetName: 'Sheet1'
    //       }
    //     ]
    //     json2excel(excelDatas, '表格大标题', true, 'xlsx')
    // })

    var excelDatas = [
        {
            tHeader: ['表头1', '表头2', '表头3', '表头4',],
            filterVal: ['title1', 'title2', 'title3', 'title4'],
            tableDatas: [ 
                {title1: "内容1",title2: "内容2",title3: "内容3",title4: "内容4"},
                {title1: "内容11",title2: "内容22",title3: "内容32",title4: "内容44"},
                {title1: "内容111",title2: "内容222",title3: "内容333",title4: "内容444"},
            ],
            sheetName: 'Sheet1'
        }
    ]
    json2excel(excelDatas, '表格大标题', true, 'xlsx')
}

     

  }
}
</script>
<!-- 加了scoped，则是仅在此组件里生效 -->
<style scoped>
 
.column-item{display: block;height:20px;width:30px;background-color:#d7d7d7; border-radius: 4px;    margin:0 auto;}
.column-color1{background-color:#4b7902;}
.column-color2{background-color:#d9001b;}
.column-color3{background-color:#8080ff;}
.column-color4{background-color:#d7d7d7;}

.column-color11{color:#4b7902;}
.column-color22{color:#d9001b;}
.column-color33{color:#8080ff;}
.column-color44{color:#d7d7d7;}

.column-txt{display: block;}
</style>
