<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="el-icon-search"
            style="margin-bottom: 20px" />
        </div>
        <div class="tree-container">
          <div style="margin-bottom: 10px;">
            <el-checkbox v-model="queryParams.checkSub" @change="changeCheckBox">是否关联下级机构</el-checkbox>
          </div>
          <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false"
            :filter-node-method="filterNode" ref="tree" node-key="id" :default-expanded-keys="defaultKeys"
            :default-checked-keys="defaultKeys" @node-click="handleNodeClick" />
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

          <el-form-item label="设备名称" prop="deviceName">
            <el-input v-model="queryParams.deviceName" placeholder="请输入设备名称" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="资产类别" prop="assetType">

            <el-select style="width: 100%;" v-model="queryParams.assetType" placeholder="请选择">
              <el-option v-for="dict in dict.type.sys_asset_type" :key="dict.value" :label="dict.label"
                :value="`${dict.value}`"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="设备分类" prop="deviceType">

            <el-select style="width: 100%;" v-model="queryParams.deviceType" placeholder="请选择">
              <el-option v-for="dict in dict.type.sys_device_type" :key="dict.value" :label="dict.label"
                :value="`${dict.value}`"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
              v-hasPermi="['system:device:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
              v-hasPermi="['system:device:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['system:device:remove']">删除</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="所属机构" align="center" prop="orgName" />
          <el-table-column label="设备名称" align="center" prop="deviceName" />


          <el-table-column label="资产类别" align="center" key="assetType" prop="assetType" width="80">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_asset_type" :value="scope.row.assetType" />
            </template>
          </el-table-column>

          <el-table-column label="设备分类" align="center" key="deviceType" prop="deviceType" width="80">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_device_type" :value="scope.row.deviceType" />
            </template>
          </el-table-column>


          <el-table-column label="设备品牌" align="center" prop="deviceBrand" />
          <el-table-column label="验收日期" align="center" prop="checkTime" width="160">
          </el-table-column>
          <el-table-column label="保修期限" align="center" prop="maintenanceTerm" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['system:device:edit']">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                v-hasPermi="['system:device:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
          @pagination="getList" />
      </el-col>
    </el-row>







    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="10">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="form.deviceName" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="所属机构" prop="orgId">
              <tree-select v-model="form.orgId" :options="deptOptions" :show-count="true" :normalizer="tenantIdnormalizer"
                :props="{ checkStrictly: true, label: 'name' }" placeholder="请选择归属机构" @select="changeSelect">
              </tree-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="资产类别" prop="assetType">
              <el-select style="width: 100%;" v-model="form.assetType" placeholder="请选择">
                <el-option v-for="dict in dict.type.sys_asset_type" :key="dict.value" :label="dict.label"
                  :value="`${dict.value}`"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="设备分类" prop="deviceType">
              <el-select style="width: 100%;" v-model="form.deviceType" placeholder="请选择">
                <el-option v-for="dict in dict.type.sys_device_type" :key="dict.value" :label="dict.label"
                  :value="`${dict.value}`"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item v-if="form.deviceType == 2" label="主机" prop="hostId">
              <el-select v-model="form.hostId" placeholder="请选择">
                <el-option v-for="item in hostList" :key="item.id" :label="item.deviceName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item v-if="form.deviceType == 2" label="通道号" prop="channel">
              <el-input v-model="form.channel" placeholder="请输入" />
            </el-form-item>
          </el-col>

        </el-row>


        <el-row>
          <el-col :span="10">
            <el-form-item label="设备品牌" prop="deviceBrand">
              <el-input v-model="form.deviceBrand" placeholder="请输入" maxlength="30" />
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item style="width: 517px;" label="验收日期" prop="checkTime">
              <el-date-picker clearable v-model="form.checkTime" type="date" value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择时间">
              </el-date-picker>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>

          <el-col :span="10">
            <el-form-item label="保修期限" prop="maintenanceTerm">
              <el-input v-model="form.maintenanceTerm" placeholder="请输入" maxlength="11" />
            </el-form-item>
          </el-col>

        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import tableList from '@/mixins/tableList'
import treeselect from '@riophae/vue-treeselect'
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { deptTreeSelect } from "@/api/system/public";
import { listDevice, getDevice, delDevice, addDevice, updateDevice, getHostByOrgId } from "@/api/system/device";
export default {
  /** 引入基础minxins*/
  mixins: [tableList],
  dicts: ['sys_asset_type', 'sys_device_type'],
  name: "Device",
  components: { treeselect },
  data() {
    return {
      checkList: [],
      roleOptions: [],
      defaultKeys: [],
      //是否关联下级
      checked: false,
      defaultProps: {
        children: "children",
        label: "name"
      },
      rules: {
        deviceName: [
          { required: true, message: '请输入设备名称', trigger: 'change' },
        ],
        orgId: [
          { required: true, message: '请选择所属机构', trigger: 'blur' },
        ],
        assetType: [
          { required: true, message: '请选择资产类别', trigger: 'blur' },
        ],
        hostId: [{ required: true, message: '请选择主机', trigger: 'blur' }],
        channel: [{ required: true, message: '请输入通道号', trigger: 'change' }],
        deviceType: [
          { required: true, message: '请选择设备分类', trigger: 'blur' },

        ],



      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      //搜索tree
      deptName: null,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      deviceList: [],
      //主机集合
      hostList: [],
      deviceType: 0,

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orgId: null,
        orgName: null,
        deviceName: null,
        assetType: null,
        deviceType: null,
        deviceBrand: null,
        checkTime: null,
        maintenanceTerm: null,
        hostId: null,
        channel: null
      },
      // 表单参数
      form: {
        orgId: null,
        deviceName: null,
        assetType: null,
        deviceType: null,
        deviceBrand: null,
        checkTime: null,
        maintenanceTerm: null,
        hostId: null,
        channel: null
      },
      // 表单校验

      //修改新增中的机构树
      deptOptions: [],
    };
  },
  created() {
    this.getDeptTree();
    this.getList();
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {

    /** 下穿状态改变*/
    changeCheckBox() {
      this.getList();
    },

    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    /** 查询机构树数据 */

    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
        console.log(this.deptOptions, ' this.deptOptions')
        this.defaultKeys.push(response.data[0].id);
        this.queryParams.orgId = response.data[0].id;
        this.handleQuery();
      });
    },
    /** treeSelect组件自定义数据*/
    tenantIdnormalizer(node, instanceId) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.orgId = data.id;
      this.handleQuery();
    },
    changeSelect(val) {
      getHostByOrgId(val).then(response => {
        this.form.hostId = null;
        this.hostList = response.data;
      })
    },

    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      listDevice(this.queryParams).then(response => {
        this.deviceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
        console.log(this.deptOptions, ' this.deptOptions')
        this.defaultKeys.push(response.data[0].id);
        this.queryParams.orgId = response.data[0].id;
        this.handleQuery();
      });
    },
    tenantIdnormalizer(node, instanceId) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orgId: null,
        orgName: null,
        deviceName: null,
        assetType: null,
        deviceType: null,
        deviceBrand: null,
        checkTime: null,
        maintenanceTerm: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        delFlag: null,
        hostId: null,
        channel: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.names = selection.map(item => item.deviceName)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {

      this.reset();
      this.open = true;
      this.title = "新增";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDevice(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改";
      });
      listDevice().then(response => {
        this.hostList = response.rows;
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDevice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDevice(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const names = row.deviceName || this.names;
      this.$modal.confirm('是否确认删除名称为"' + names + '"的数据项？').then(function () {
        return delDevice(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/device/export', {
        ...this.queryParams
      }, `device_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
