<template>
  <section class="app-container">
    <el-row>
      <el-col :span="4">
        <region @selectdRegionCode="selectdRegionCode" :currentNodeKey.sync="queryParams.provinceCode"></region>
      </el-col>
      <el-col :span="20">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="名称" prop="jobName">
            <el-input v-model="queryParams.deviceName" placeholder="请输入名称" clearable size="small" style="width: 240px"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="cyan" 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 size="mini" type="primary" icon="el-icon-plus" @click="handleAdd" v-hasPermi="['system:device:add']">增加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['monitor:job:remove']">批量删除</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleClean" v-hasPermi="['monitor:job:remove']">清空
            </el-button>
          </el-col> -->
          <!-- <el-col :span="1.5">
            <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['monitor:job:export']">导出
            </el-button>
          </el-col> -->
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center">
          </el-table-column>
          <el-table-column prop="deviceId" align="center" label="设备SN">
          </el-table-column>
          <el-table-column prop="deviceName" align="center" label="设备名称">
          </el-table-column>
          <!-- <el-table-column prop="deviceCode" align="center" label="设备编码">
          </el-table-column>
          <el-table-column prop="deviceType" align="center" label="类型">
          </el-table-column>
          <el-table-column prop="deviceModel" align="center" label="装置模型">
          </el-table-column> -->
          <el-table-column prop="proName" align="center" label="省份">
          </el-table-column>
          <el-table-column prop="cityName" align="center" label="市">
          </el-table-column>
          <el-table-column prop="disName" align="center" label="区">
          </el-table-column>
          <!-- <el-table-column prop="status" align="center" label="在线状态">
          </el-table-column> -->
          <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-plus" @click="handleAddnode(scope.row)">新增节点
              </el-button>
              <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-view" @click="handleview(scope.row)">查看节点
              </el-button>
              <el-button class="text-danger" size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                v-hasPermi="['system:device:edit']">删除</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="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="设备SN" prop="deviceId">
          <el-input v-model="form.deviceId" placeholder="请输入设备SN" />
        </el-form-item>
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
        </el-form-item>
        <!-- <el-form-item label="设备编码" prop="deviceCode">
          <el-input v-model="form.deviceCode" placeholder="请输入设备编码" />
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceType">
          <el-input v-model="form.deviceType" placeholder="请输入设备类型" />
        </el-form-item>
        <el-form-item label="设备型号" prop="deviceModel">
          <el-input v-model="form.deviceModel" placeholder="请输入设备型号" />
        </el-form-item> -->
        <el-form-item label="产品" prop="productId">
          <el-select v-model="form.productId" clearable placeholder="请选择">
            <el-option v-for="item in productSelectList" :key="item.id" :label="item.productName" :value="item.productId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户" prop="userId">
          <el-select v-model="form.userId" clearable placeholder="请选择" @change="userIdChange">
            <el-option v-for="item in userSelectList" :key="item.id" :label="item.nickName" :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目" prop="projectId">
          <el-select v-model="form.projectId" clearable placeholder="请选择">
            <el-option v-for="item in projectSelectList" :key="item.id" :label="item.projectName" :value="item.projectId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="国家行政区 省" prop="proCode">
          <el-select v-model="form.proCode" clearable placeholder="请选择" @change="provinceCodeChange">
            <el-option v-for="item in provinceSelectList" :key="item.code" :label="item.cityName" :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="国家行政区 市" prop="cityCode">
          <el-select v-model="form.cityCode" clearable placeholder="请选择" @change="cityCodeChange">
            <el-option v-for="item in citySelectList" :key="item.code" :label="item.cityName" :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="国家行政区 区" prop="disCode">
          <el-select v-model="form.disCode" clearable placeholder="请选择">
            <el-option v-for="item in districtSelectList" :key="item.code" :label="item.cityName" :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
      </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>

    <!-- 节点列表弹框 -->
    <el-dialog title="节点列表" :visible.sync="nodeDialog">
      <!-- <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="nodeMultiple" @click="batchHandleDeletenode">批量删除</el-button> -->
      <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="nodeMultiple" @click="batchHandleDeletenode">批量删除</el-button>
      <el-table :data="nodeData" @selection-change="nodeHandleSelectionChange">
        <el-table-column type="selection" width="55" align="center">
        </el-table-column>
        <el-table-column prop="deviceId" label="设备SN"></el-table-column>
        <el-table-column prop="nodeId" label="节点SN"></el-table-column>
        <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="handleUpdatenode(scope.row)">修改</el-button>
            <el-button class="text-danger" size="mini" type="text" icon="el-icon-delete" @click="handleDeletenode(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 添加节点参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="nodeOpen" width="500px" append-to-body>
      <el-form ref="nodeForm" :model="nodeForm" :rules="nodeRules" label-width="100px">
        <el-form-item label="设备SN" prop="deviceId">
          <el-input v-model="nodeForm.deviceId" disabled placeholder="请输入设备SN" />
        </el-form-item>
        <el-form-item label="节点名称" prop="nodeDataId">
          <el-select v-model="nodeForm.nodeDataId" :disabled="!!nodeForm.id" clearable placeholder="请选择">
            <el-option v-for="item in productNodeSelectList" :key="item.id" :label="item.nodeName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="节点SN" prop="nodeId">
          <el-input v-model="nodeForm.nodeId" placeholder="请输入节点SN" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveNode">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import Region from "@/components/Region";
import {
  list,
  info,
  add,
  update,
  del,
} from "@/api/hardware/device";
// import { nodeList, addNode, nodeInfo, delNode, nodeSelect } from "@/api/system/device/node";
import { select as productSelect } from "@/api/hardware/product";
import { select as projectSelect } from "@/api/hardware/project";
import { userSelect } from "@/api/system/user";
import { list as provinceList, getProvinceByParent } from "@/api/hardware/province";
import { productNodeList, productNodeSelect } from "@/api/hardware/productNode";
import { deviceNodeList, deviceNodeSave, deviceNodeInfo, deviceNodeDel, deviceNodeSelect } from "@/api/hardware/deviceNode";

export default {
  name: "DeviceList",
  components: {
    Region,
  },
  // watch: {
  //   'form.proCode': function(code) {
  //     this.provinceCodeChange(code)
  //   },
  //   'form.cityCode': function(code) {
  //     this.cityCodeChange(code)
  //   },
  // },
  data () {
    return {
      snapDeviceInfo: {},
      // 产品下拉列表
      productSelectList: [],
      userSelectList: [],
      projectSelectList: [],
      provinceSelectList: [],
      citySelectList: [],
      districtSelectList: [],
      productNodeSelectList: [],
      // 选中数组
      ids: [],
      nodeIds: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      nodeMultiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      nodeDialog: false,
      nodeOpen:false,
      // 表单参数
      form: {},
      nodeForm: {},
      // 表格数据
      tableData: null,
      nodeData: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      rules: {
        deviceId: [
          { required: true, message: "设备SN不能为空", trigger: "blur" },
        ],
        deviceName: [
          { required: true, message: "设备名称不能为空", trigger: "blur" },
        ],
        deviceType: [
          { required: true, message: "设备编码不能为空", trigger: "blur" },
        ],
        productId: [
          { required: true, message: "产品不能为空", trigger: "blur" },
        ],
        userId: [
          { required: true, message: "客户不能为空", trigger: "blur" },
        ],
        projectId: [
          { required: true, message: "项目不能为空", trigger: "blur" },
        ],
        proCode: [
          { required: true, message: "省不能为空", trigger: "blur" },
        ],
        cityCode: [
          { required: true, message: "市不能为空", trigger: "blur" },
        ],
        disCode: [
          { required: true, message: "区不能为空", trigger: "blur" },
        ],
      },
      nodeRules: {
        nodeId: [
          { required: true, message: "节点SN不能为空", trigger: "blur" },
        ],
        deviceId: [
          { required: true, message: "设备SN不能为空", trigger: "blur" },
        ],
        nodeDataId: [
          { required: true, message: "节点真正ID不能为空", trigger: "blur" },
        ],
      }
    };
  },
  created () {
    productSelect().then(({ code, msg, select }) => {
      if (code == 200) {
        this.productSelectList = select;
      } else {
        this.$message.error(msg);
      }
    })
    userSelect().then(({ code, msg, select }) => {
      if (code == 200) {
        this.queryUserSelectList = select;
        this.userSelectList = select;
      } else {
        this.$message.error(msg);
      }
    })
    provinceList().then(({ code, msg, rows }) => {
      if (code == 200) {
        this.provinceSelectList = rows;
      } else {
        this.$message.error(msg);
      }
    })
    this.getList();
  },
  methods: {
    selectdRegionCode ({ code }) {
      this.queryParams.provinceCode = code;
      this.handleQuery();
    },
    userIdChange (userId) {
      delete this.form.projectId;
      this.projectSelectList = [];
      if (!userId) return;
      projectSelect({ userId }).then(({ code, msg, select }) => {
        if (code == 200) {
          this.projectSelectList = select;
        } else {
          this.$message.error(msg);
        }
      })
    },
    getProvinceByParent (id) {
      return new Promise((resolve, reject) => {
        getProvinceByParent(id).then(({ code, msg, data }) => {
          if (code == 200) {
            resolve(data);
          } else {
            this.$message.error(msg);
            reject({ msg, code })
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    async provinceCodeChange (id) {
      delete this.form.cityCode;
      delete this.form.disCode;
      this.citySelectList = await this.getProvinceByParent(id);
    },
    async cityCodeChange (id) {
      delete this.form.disCode;
      this.districtSelectList = await this.getProvinceByParent(id);
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.queryParams = {};
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 获取设备数据列表
    getList () {
      list(this.queryParams).then((response) => {
        this.tableData = response.rows;
        this.total = response.total;
      });
    },

    // 获取节点数据列表
    getListnode ({ deviceId }) {
      deviceNodeList({ deviceId }).then((response) => {
        this.nodeData = response.rows;
      });
    },

    // 取消按钮
    cancel () {
      this.open = false;
      this.nodeOpen = false;
      this.reset();
    },

    // 表单重置
    reset () {
      this.form = {
        deviceId: "",
        deviceType: "",
        deviceName: "",
        status: "0",
      };
      this.nodeForm = {
        nodeId: "",
        deviceId: "",
        nodeDataId: "",
      };
      this.resetForm("form");
      this.resetForm("nodeForm");
    },

    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    // nodeHandleSelectionChange(){},
    nodeHandleSelectionChange (selection) {
      this.nodeIds = selection.map((item) => item.id);
      this.nodeMultiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "添加设备";
    },

    // 新增节点
    handleAddnode (row) {
      productNodeSelect({productId: row.productId}).then(({ code, msg, select }) => {
        if (code == 200) {
        this.productNodeSelectList = select;
        } else {
          this.$message.error(msg);
        }
      })
      this.reset();
      this.nodeOpen = true;
      this.title = "添加设备节点";
      this.nodeForm.deviceId = row.deviceId;
    },

    // 查看节点
    handleview (row) {
      this.nodeDialog = true;
      this.snapDeviceInfo = row;
      this.getListnode(row)
    },

    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      info(row.id).then(({ code, info, msg }) => {
        if (200 == code) {
          this.provinceCodeChange(info.proCode);
          this.cityCodeChange(info.cityCode);
          this.form = info;
          this.open = true;
          this.title = "修改设备";
        } else {
          this.msgError(msg);
        }
      })
    },

    /** 修改节点 */
    handleUpdatenode(row){
      this.reset();
      productNodeSelect({productId: this.snapDeviceInfo.productId}).then(({ code, msg, select }) => {
        if (code == 200) {
        this.productNodeSelectList = select;
        } else {
          this.$message.error(msg);
        }
      })
      this.nodeOpen = true;
      this.title = "修改设备节点";
      this.nodeForm = row;
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // debugger
          if (this.form.id != undefined) {
            update(this.form).then(res => {
              if (200 == res.code) {
                this.msgSuccess(this.title + "成功");
                this.open = false;
                this.getList();
              } else {
                this.msgSuccess(res.msg);
              }

            });
          } else {
            add(this.form).then(res => {
              if (200 == res.code) {
                this.msgSuccess(this.title + "成功");
                this.open = false;
                this.getList();
              } else {
                this.msgSuccess(res.msg);
              }
            });
          }
        }
      });
    },

    // 节点提交
    saveNode: function () {
      deviceNodeSave(this.nodeForm).then((res) => {
        if (200 == res.code) {
          this.msgSuccess(this.title + "成功");
          this.nodeOpen = false;
          this.getList();
        } else {
          this.msgSuccess(res.msg);
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return del(ids);
      }).catch(() => { }).then(res => {
        if (200 == res.code) {
          this.getList();
          this.msgSuccess("删除成功");
        } else {
          this.msgSuccess(res.msg);
        }
      }).catch(res => { })
    },

    handleDeletenode (row) {
      const ids = row.id || this.ids;
      this.$confirm("是否确认删除?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return deviceNodeDel(ids);
        })
        .then((res) => {
          if (200 == res.code) {
            this.getListnode(row);
            this.msgSuccess("删除成功");
          } else {
            this.msgError(res.msg);
          }
        })
        .catch((res) => { });
    },
    // 批量删除节点
    batchHandleDeletenode () {
      this.$confirm("是否确认删除?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return deviceNodeDel(this.nodeIds);
        })
        .then((res) => {
          if (200 == res.code) {
            this.getListnode(...this.nodeData);
            this.msgSuccess("删除成功");
          } else {
            this.msgError(res.msg);
          }
        })
        .catch((res) => { });
    },

    // 页码尺寸改变
    handleSizeChange (val) {
      this.queryForm.pagesize = val;
      this.getList();
    },
    // 页码改变
    handleCurrentChange (val) {
      this.queryForm.page = val;
      this.getList();
    },
    // handleSelectionChange(val) {
    //   this.multipleSelection = val;
    // },
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`);
    },
    // 对话框的关闭
    handleClose (done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => { });
    },
  },
};
</script>


<style></style>
