<!--
 * @Author: your name
 * @Date: 2022-01-08 10:37:10
 * @LastEditTime: 2022-01-08 10:37:11
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \goldenPig\src\views\basic-data\device-admin\DeviceAdmin.vue
-->
<template>
  <div class="device">
    <el-card>
      <el-form :inline="true" label-width="100px" size="mini" :model="form">
        <el-form-item label="采集牧场" v-if="userItem.type !== 2">
          <el-select v-model="form.farm">
            <el-option
              v-for="item in farmList"
              :key="item.id"
              :value="item.id"
              :label="item.farmName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备编码">
          <el-input v-model="form.registeCode"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <br>
    <div>
      <new-table
        v-loading="loading"
        :height="600"
        :title="devTitle"
        :listData="list"
        :tableItems="tableItems">
        <template #right>
          <el-button type="primary" size="mini" @click="add">新增设备</el-button>
        </template>
        <template #stage="scope">
          <span>{{ getStage(scope.row.stage) }}</span>
        </template>
        <template #dong="scope">
          <span>{{ scope.row.penName }}{{ scope.row.unitName }}</span>
        </template>
        <template #canStatus="scope">
          <span v-if="scope.row.canStatus === 0" style="color: #52c41a">正常</span>
          <span v-else style="color: red">异常</span>
        </template>
        <template #handler="scope">
<!--          <el-button type="text" @click="edit(scope.row)">编辑</el-button>-->
<!--          <el-divider direction="vertical"></el-divider>-->
          <el-popconfirm
            title=" 确定要删除这个区域吗？"
            @confirm="del(scope.row)"
          >
            <el-button type="text" size="mini" slot="reference" style="color: red">删除</el-button>
            >
          </el-popconfirm>
        </template>
      </new-table>
      <table-footer
        :totals="total"
        :size="pageSize"
        @sizeChange="sizeChange"
        @pageChange="pageChange"
      ></table-footer>
    </div>
    <el-dialog
      width="30%"
      v-loading="formLoading"
      element-loading-text="提交中,请稍后"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      :title="showType ? '编辑设备': '新增设备'"
      :visible.sync="dialogVisible">
      <el-form  :rules="rules" ref="ruleForm" label-width="100px" :model="devForm" size="mini">
        <el-form-item label="设备编码" prop="deviceCode">
          <el-input v-model="devForm.deviceCode"></el-input>
        </el-form-item>
        <el-form-item label="芯片编码" prop="registeCode">
          <el-input v-model="devForm.registeCode"></el-input>
        </el-form-item>
        <el-form-item label="栋舍" prop="pigpenId">
          <el-select v-model="devForm.pigpenId" @change="getUnitList">
            <el-option v-for="item in penList" :key="item.id" :value="item.id" :label="item.pigpenName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单元" prop="unitId">
          <el-select :disabled="selectUnit" v-model="devForm.unitId" @change="getUnitName">
            <el-option v-for="item in unitList.children" :key="item.id" :value="item.id" :label="item.pigpenName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="ip地址" prop="serverIp">
          <el-input v-model="devForm.serverIp"></el-input>
        </el-form-item>
        <el-form-item label="端口号" prop="port">
          <el-input v-model="devForm.port"></el-input>
        </el-form-item>
        <el-form-item label="阶段" prop="stage">
          <el-select v-model="devForm.stage">
            <el-option v-for="item in stageList" :key="item.value" :value="item.value" :label="item.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { mapState, mapActions } from "vuex";
import { getDeviceList, addDeviceList, delDeviceList } from "@/utils/apis/device-admin/deviceAdmin";
import NewTable from "@/components/newTable/NewTable";
import TableFooter from "@/components/TableFooter";
import { basePigpenList } from "@/utils/apis/basic-data/houseAdmin";
import { getFilter } from "@/utils";

export default {
  name: 'DeviceAdmin',
  components: {
    NewTable,
    TableFooter
  },
  computed: {
    ...mapState(["stageList", "farmList"]),
  },
  data() {
    return {
      form: {
        farm: '',
        registeCode: '',
      },
      devTitle: '设备列表',
      pageNum: 1,
      pageSize: 20,
      total: 0,
      loading: true,
      list: [],
      tableItems: [
        {
          prop: "id",
          label: "注册id",
          minWidth: "50",
          slotName: "id",
        },
        {
          prop: "registerTime",
          label: "芯片编码",
          minWidth: "100",
          slotName: "registerTime",
        },
        {
          prop: 'deviceCode',
          label: '设备编码',
          minWidth: "100",
          slotName: "deviceCode",
        },
        {
          prop: "registeCode",
          label: "注册编码",
          minWidth: "100",
          slotName: "registeCode",
        },
        {
          prop: "farmName",
          label: "牧场名",
          minWidth: "100",
          slotName: "farmName",
        },
        {
          prop: "farmCode",
          label: "牧场编码",
          minWidth: "100",
          slotName: "farmCode",
        },
        {
          label: "牧场编码",
          minWidth: "50",
          slotName: "stage",
        },
        {
          label: "栋舍",
          minWidth: "100",
          slotName: "dong",
        },
        {
          prop: 'lastTime',
          label: "最后上传时间",
          minWidth: "100",
          slotName: "lastTime",
        },
        {
          label: "设备状态",
          minWidth: "50",
          slotName: "canStatus",
        },
        {
          label: "操作",
          minWidth: "50",
          slotName: "handler",
        }
      ],
      formLoading: false,
      dialogVisible: false,
      showType: false,
      devForm: {
        deviceCode: '',
        pigpenId: '',
        unitId: '',
        serverIp: '',
        port: '',
        stage: '',
        registeCode: '',
      },
      penList: [],
      unitList: {},
      selectUnit: true,
      penName: '',
      unitName: '',
      rules: {
        deviceCode: [{  required: true, message: '请输入设备编码', trigger: 'blur' }],
        registeCode: [{  required: true, message: '请输入注册编码', trigger: 'blur' }],
        pigpenId: [{  required: true, message: '请选择栋舍', trigger: 'change' }],
        unitId: [{  required: true, message: '请选择单元', trigger: 'change' }],
        serverIp: [{  required: true, message: '请输入ip', trigger: 'blur' }],
        port: [{  required: true, message: '请输入端口号', trigger: 'blur' }],
        stage: [{  required: true, message: '请选择阶段', trigger: 'change' }],
      }
    }
  },
  methods: {
    ...mapActions(["GetFarm"]),
    // 修改size
    sizeChange(val) {
      this.size = val;
      this.init();
    },
    // 修改页数
    pageChange(val) {
      this.pageSize = val;
      this.init();
    },
    init() {
      let params = {
        farmId: this.form.farm,
        pageNo: this.pageNum,
        pageSize: this.pageSize
      }
      if(this.form.registeCode !== '') {
        params.registeCode = this.form.registeCode
      }
      getDeviceList(params).then(res => {
        this.loading = false
        if(res.code === 10000) {
          this.list = res.data.records;
          this.total = res.data.total;
        }
      })
    },
    getStage(id) {
      let data = this.stageList.find((item) => {
        return item.value == id;
      });
      return data.label;
    },
    add() {
      this.dialogVisible = true;
      this.showType = false;
    },
    edit() {},
    // 拿到所有栋舍
    initPen() {
      let params = {
        farmId: this.form.farm
      }
      basePigpenList(params).then(res => {
        if(res.code === 10000) {
          this.penList = res.data.records;
        }
      })
    },
    getUnitList(val) {
      this.unitList = getFilter(this.penList,val)[0];
      let selectPlanClass = {};
      selectPlanClass = this.penList.find((item) => {
        return item.id === val
      })
      this.penName = selectPlanClass.pigpenName;
      if(this.unitList.children.length < 0) {
        this.$message.error('该栋舍下暂无单元！')
        this.selectUnit = true;
      } else {
        this.selectUnit = false;
      }
    },
    getUnitName(val) {
      let selectPlanClass = {};
      selectPlanClass = this.unitList.children.find((item) => {
        return item.id === val
      })
      this.unitName = selectPlanClass.pigpenName;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.showType) {
            return
          } else {
            this.formLoading = true;
            let obj = {
              penName: this.penName,
              unitName: this.unitName,
              farmId: this.form.farm
            }
            let params = Object.assign(this.devForm, obj);
            addDeviceList(params).then(res => {
              this.formLoading = false;
              if(res.code === 10000) {
                this.dialogVisible = false;
                this.init();
                this.$message.success(res.message);
              } else {
                this.$message.error(res.message);
              }
            }).catch(() => {
              this.formLoading = false;
            })
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    del(item) {
      let ids = [item.id];
      delDeviceList(ids).then(res => {
        if(res.code === 10000) {
          this.init()
          this.$message.success('删除成功！');
        } else {
          this.message.error(res.message)
        }
      })
    }
  },
  created() {
    this.userItem = JSON.parse(localStorage.getItem("gold_UserItem"));
    this.GetFarm()
  },
  mounted() {
    if(this.userItem.type === 0) {
      this.form.farm = this.farmList[0].id;
    } else {
      this.form.farm = parseInt(this.userItem.farmId);
    }
    this.init();
    this.initPen();
  },
};
</script>
<style scoped>
  .device{
    box-sizing: border-box;
    padding: 20px;
  }
  .x-from {
    box-sizing: border-box;
  }
</style>
