<template>
  <div class="iot-child-device">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="设备名称" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </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">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row> -->

    <el-table v-loading="loading" :data="deviceList">
      <el-table-column type="index" label="序号" align="center" :index="indexFormatter" width="80px"></el-table-column>
      <el-table-column label="设备名称" align="left" prop="deviceName" />
      <el-table-column label="所属型号" align="left" prop="modelName" />
      <el-table-column label="设备key" align="left" prop="deviceKey" />
      <el-table-column label="设备类型" align="left" width="120px" prop="deviceTypeName" />
      <el-table-column label="设备状态" align="center" width="120" prop="deviceStatus">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.deviceState === 'ONLINE'">在线</el-tag>
          <el-tag type="danger" v-else-if="scope.row.deviceState === 'OFFLINE'">离线</el-tag>
          <el-tag type="danger" v-else-if="scope.row.deviceState === 'OUTLINE'">脱线</el-tag>
          <el-tag type="info" v-else-if="scope.row.deviceState === 'UNACTIVE'">未激活</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" width="160px" prop="createTime" />
      <el-table-column
        label="操作"
        align="center"
        width="200px"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handleDetails(scope.row)"
          >详情</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button> -->
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iot: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-dialog class="eldialog-wrap" :close-on-click-modal="false" :title="title" :visible.sync="open" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属型号：" prop="modelId">
          <el-input
            v-model="form.modelName"
            placeholder="点击选择型号"
            @focus="openModelTableSelectDialog()"
          />
        </el-form-item>

        <el-form-item label="设备类型：" prop="deviceType">
          <el-select
            disabled
            v-model="form.deviceType"
            style="width: 100%;"
            placeholder="请选择设备类型"
            clearable
          >
            <el-option
              :label="keys"
              :value="vals"
              v-for="(keys, vals) in deviceTypeList"
              :key="vals"
            />
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="父设备：" prop="parentId" >
          <el-input
            v-model="form.parentName"
            placeholder="点击选择父设备"
            disabled
          />
        </el-form-item>-->
        <el-form-item label="设备名称：" prop="deviceName">
          <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
        </el-form-item>

        <el-form-item label="设备KEY：" prop="deviceKey">
          <el-input :disabled="title === '修改子设备'" v-model="form.deviceKey" placeholder="请输入设备KEY" />
        </el-form-item>

        <el-form-item label="线路类型：" prop="lineType">
          <el-select v-model="form.lineType" style="width: 100%;" placeholder="请选择线路类型" clearable>
            <el-option :label="keys" :value="vals" v-for="(keys, vals) in lineTypeOpt" :key="vals" />
          </el-select>
        </el-form-item>

        <el-form-item label="参数设置：">
          <span style="color: red; font-size: 12px;">*注意：锁定即参数不可修改；未锁则可以修改。</span>
          <div class="form-params-wrap">
            <param-wrap ref="paramWrap" typeKeys></param-wrap>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="submitForm">确 定</el-button>
        <el-button size="mini" @click="open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="选择"
      :visible.sync="selectTableShow"
      width="75%"
      top="10vh"
      class="select-table-dialog"
      :close-on-click-modal="false"
    >
      <select-table-wrap
        v-if="selectTableShow"
        :tableOption="tableSelectOption.tableOpt"
        :queryOption="tableSelectOption.queryOpt"
        :tableList="tableSelectOption.tableList"
        @parentGetList="childGetList($event)"
        :otherOption="tableSelectOption.otherOption"
        @returnEvent="returnEvent($event)"
      />

      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="resuleClick">确 定</el-button>
        <el-button size="mini" @click="() =>{selectTableShow = false}">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  listDevice,
  delDevice,
  addDevice,
  updateDevice,
  listDeviceTypeList,
  getDevice
} from "@/api/tenant/device";
import { listModel, getModel } from "@/api/iot/model";
import SelectTableWrap from "@/components/SelectTable/index";
import ParamWrap from "@/components/ParamWrap/deviceParam";
const lineTypeOpt = {
  MAIN: "总路",
  BRANCH: "支路"
};
export default {
  name: "",
  props: ["sourceId", "pDevcieInfo"],
  components: {
    SelectTableWrap,
    ParamWrap
  },
  data() {
    return {
      lineTypeOpt,
      selectTableShow: false,
      tableSelectOption: {},
      selectResult: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        modelId: null,
        parentId: null,
        deviceCode: null,
        deviceName: null,
        deviceStatus: null,
        deviceKey: null,
        deviceType: null,
        parentId: ""
      },
      open: false,
      title: "",
      showSearch: true,
      // 设备表格数据
      deviceList: [],
      total: 0,
      form: {},
      // 表单校验
      rules: {
        modelId: [
          { required: true, message: "所属型号不能为空", trigger: "blur" }
        ],
        deviceType: [
          { required: true, message: "设备类型不能为空", trigger: "blur" }
        ],
        parentId: [
          { required: true, message: "父设备不能为空", trigger: "blur" }
        ],
        deviceName: [
          { required: true, message: "设备名称不能为空", trigger: "blur" }
        ],
        lineType: [
          { required: true, message: "线路类型不能为空", trigger: "blur" }
        ],
        deviceKey: [
          {
            required: true,
            validator: this.chenking_deviceKey,
            trigger: "blur"
          }
        ]
      },
      deviceTypeList: []
    };
  },
  created() {
    this.getDeviceTypeList();
    this.getList();
  },
  methods: {
    // 查询回调
    childGetList(data) {
      this.modelChildList(data);
    },
    // 点击或者双击数据回调
    returnEvent(data) {
      if (data.type === "dblclick") {
        this.getModelInfoById(data.value.modelId);
        this.form.modelId = data.value.modelId;
        this.form.modelName = data.value.modelName;
        this.form.deviceType = data.value.deviceType;
        this.form.prodKey = data.value.prodKey;
        // this.deviceTypeChange(this.form.deviceType);
        this.selectTableShow = false;
      } else if (data.type === "click") {
        this.selectResult = {};
        this.selectResult.modelId = data.value.modelId;
        this.selectResult.modelName = data.value.modelName;
        this.selectResult.deviceType = data.value.deviceType;
        this.selectResult.prodKey = data.value.prodKey;
      }
    },
    // 根据 型号id 获取 型号详情
    getModelInfoById(modelId) {
      getModel(modelId).then(res => {
        this.$refs.paramWrap.setList(res.data.paramList || []);
      });
    },
    modelChildList(data) {
      listModel(Object.assign(data.page, data.param, { selected: 1 })).then(
        response => {
          this.tableSelectOption.tableList = response.rows;
          this.tableSelectOption.queryOpt.page.total = Number(response.total);
        }
      );
    },
    // 点击确定按钮
    resuleClick() {
      this.form.modelId = this.selectResult.modelId;
      this.form.prodKey = this.selectResult.prodKey;
      this.form.modelName = this.selectResult.modelName;
      this.form.deviceType = this.selectResult.deviceType;
      // this.deviceTypeChange(this.form.deviceType);
      this.getModelInfoById(this.selectResult.modelId);
      this.selectTableShow = false;
    },
    // 打开厂商选择窗口 ——表格
    openModelTableSelectDialog() {
      this.selectResult = {};
      this.tableSelectOption = {
        otherOption: {
          tableType: "model"
        },
        queryOpt: {
          disable: false,
          labelWidth: "68px",
          params: {
            modelName: "",
            modelCode: "",
            deviceType: "MINIATURE_BREAKER"
          },
          page: {
            pageSize: 10,
            pageNum: 1,
            total: 0
          },
          inline: true,
          queryChilds: [
            {
              style: "",
              placeholder: "型号名称",
              clearable: true,
              label: "型号名称",
              type: "input",
              key: "modelName",
              size: "small",
              value: ""
            }
          ]
        },
        tableOpt: {
          loading: false,
          rowKey: "deviceId",
          selection: false,
          maxHeight: "45vh",
          childs: [
            {
              style: "",
              label: "厂商名称",
              type: "",
              prop: "vendorName",
              align: "left",
              width: "200",
              "show-overflow-tooltip": false,
              tempType: "span"
            },
            {
              style: "",
              label: "型号名称",
              type: "",
              prop: "modelName",
              align: "left",
              width: "200",
              "show-overflow-tooltip": false,
              tempType: "span"
            },
            {
              style: "",
              label: "设备类型",
              type: "",
              prop: "deviceTypeName",
              align: "left",
              width: "120",
              "show-overflow-tooltip": false,
              tempType: "span"
            },
            {
              style: "",
              label: "产品PK",
              type: "",
              prop: "prodKey",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span"
            },
            {
              style: "",
              label: "产品密钥",
              type: "",
              prop: "prodSecret",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span"
            }
          ],
          tableList: {
            type: Array
          }
        },
        tableList: []
      };
      this.selectTableShow = true;
    },
    // 查询设备类型列表
    getDeviceTypeList() {
      listDeviceTypeList().then(response => {
        this.deviceTypeList = response.data;
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加子设备";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const _this = this;
      getDevice(row.deviceId).then(response => {
        _this.form = response.data;
        _this.open = true;
        _this.title = "修改子设备";
        setTimeout(() => {
          _this.$refs.paramWrap.setList(response.data.paramList || []);
        }, 100);
      });
    },
    indexFormatter(val) {
      return (
        val + 1 + (this.queryParams.pageNum - 1) * this.queryParams.pageSize
      );
    },
    /** 查询设备列表 */
    getList() {
      this.loading = true;
      this.queryParams.parentId = this.sourceId;
      listDevice(this.queryParams).then(response => {
        this.deviceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleDetails(row) {
      if (row.deviceId) {
        this.$emit("toChildEvent", { deviceId: row.deviceId });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm("是否删除该选项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return delDevice(row.deviceId);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.paramList = this.$refs.paramWrap.getResult();
          if (this.form.deviceId != null) {
            updateDevice(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDevice(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 表单重置
    reset() {
      this.form = {
        modelId: null,
        modelName: "",
        parentName: this.pDevcieInfo.deviceName,
        parentId: this.pDevcieInfo.deviceId,
        deviceName: "",
        deviceType: "MINIATURE_BREAKER",
        paramList: [],
        deviceKey: "",
        lineType: ""
      };
      this.resetForm("form");
    }
  }
};
</script>
