<template>
  <div class="app-container iot-device">
    <component :is="componectVal" :sourceId="sourceId"></component>
    <div v-show="componectVal === ''">
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <!-- <el-form-item label="所属型号" prop="modelId">
          <el-select v-model="queryParams.modelId"  placeholder="所属型号" clearable size="small" @change="handleQuery">
            <el-option
              :label="doct.modelName"
              v-for="doct in queryModelOpt"
              :key="doct.modelId"
              :value="doct.modelId"
            />
          </el-select>
        </el-form-item>-->

        <el-form-item label="型号名称" prop="modelName">
          <el-input
            v-model="queryParams.modelName"
            placeholder="请输入型号名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <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 label="设备状态" prop="deviceState">
          <el-select
            v-model="queryParams.deviceState"
            placeholder="请选择设备状态"
            @change="handleQuery"
            clearable
            size="small"
          >
            <el-option
              :label="keys"
              v-for="(keys, vals) in deviceStatusOpt"
              :key="vals"
              :value="vals"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备类型" prop="deviceType">
          <el-select
            v-model="queryParams.deviceType"
            placeholder="请选择设备类型"
            @change="handleQuery"
            clearable
            size="small"
          >
            <el-option
              :label="keys"
              :value="vals"
              v-for="(keys, vals) in deviceTypeList"
              :key="vals"
            />
          </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="['iot:device:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table
        v-loading="loading"
        :data="deviceList"
        :default-sort="{prop: 'createTime', order: 'descending'}"
        @sort-change="sortChange"
      >
        <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="left" prop="parentName" /> -->
        <el-table-column label="设备状态" align="center" width="120" prop="deviceState">
          <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"
          sortable="custom"
          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)"
              v-hasPermi="['iot:device:edit']"
            >修改</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"
      />
    </div>

    <!-- 添加或修改设备对话框 -->
    <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" v-if="form.deviceType === 'MINIATURE_BREAKER'">
          <el-input
            v-model="form.parentName"
            placeholder="点击选择父设备"
            @focus="openTableSelectDialog()"
          />
        </el-form-item>

        <el-form-item label="线路类型：" prop="lineType" v-if="form.deviceType === 'MINIATURE_BREAKER'">
          <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="设备名称：" prop="deviceName">
          <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
        </el-form-item>

        <el-form-item label="设备KEY：" prop="deviceKey">
          <el-input v-model="form.deviceKey" placeholder="请输入设备KEY" />
        </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 v-if="open"></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="cancel">取 消</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 class="to-home-wrap2" @click="toTableClick" v-show="componectVal !== ''">
      <el-button icon="el-icon-d-arrow-left" title="返回列表" circle>返回列表</el-button>
    </div>
  </div>
</template>

<script>
import {
  listDevice,
  getDevice,
  delDevice,
  addDevice,
  updateDevice,
  exportDevice,
  listDeviceTypeList
} from "@/api/iot/device";
import { listModel, getModel } from "@/api/iot/model";
import SelectTableWrap from "@/components/SelectTable/index";
import DetailsWrap from "./profile/details";
import ParamWrap from "@/components/ParamWrap/deviceParam";
import axios from "axios";
const deviceStatusOpt = {
  ONLINE: "在线",
  OFFLINE: "离线",
  OUTLINE: "脱线",
  UNACTIVE: "未激活"
};
const lineTypeOpt = {
  MAIN: "总路",
  BRANCH: "支路"
};

export default {
  name: "systemDevice",
  components: {
    SelectTableWrap,
    DetailsWrap,
    ParamWrap
  },
  data() {
    return {
      deviceStatusOpt,
      lineTypeOpt,
      sourceId: "",
      componectVal: "",
      selectTableShow: false,
      tableSelectOption: {},
      selectResult: {},
      queryModelOpt: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备表格数据
      deviceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        modelId: null,
        parentId: null,
        deviceName: null,
        deviceState: null,
        deviceType: null,
        modelName: null,
        orderByColumn: "createTime",
        isAsc: "desc"
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        modelId: [
          { required: true, message: "所属型号不能为空", trigger: "change" }
        ],
        deviceType: [
          { required: true, message: "设备类型不能为空", trigger: "blur" }
        ],
        parentId: [
          { required: true, message: "父设备不能为空", trigger: "change" }
        ],
        deviceName: [
          { required: true, message: "设备名称不能为空", trigger: "blur" }
        ],
        lineType: [
          { required: true, message: "线路类型不能为空", trigger: "blur" }
        ],
        deviceKey: [
          {
            required: true,
            validator: this.chenking_deviceKey,
            trigger: "blur"
          }
        ]
      },
      deviceTypeList: {}
    };
  },
  created() {
    console.log(this.$route)
    this.init()

  },
  methods: {
    init() {
      if (this.$route.query['deviceId']) {
        this.handleDetails(this.$route.query)
      }
      this.getDeviceTypeList();
      this.initGetModelList();
      this.getList();
    },
    sortChange(column) {
      const sort = {
        isAsc: column.order === "descending" ? "desc" : "asc",
        orderByColumn: column.prop
      };
      this.queryParams = Object.assign(this.queryParams, sort);
      this.handleQuery();
    },
    indexFormatter(val) {
      return (
        val + 1 + (this.queryParams.pageNum - 1) * this.queryParams.pageSize
      );
    },
    handleDetails(row) {
      this.sourceId = row.deviceId;
      this.componectVal = "DetailsWrap";
    },
    // 跳转详情页
    toTableClick() {
      if (this.$route.query['deviceId']) {
        this.$router.push('/device/device')
      }
      this.componectVal = "";
    },
    // 打开厂商选择窗口 ——表格
    openModelTableSelectDialog() {
      this.selectResult = {};
      this.tableSelectOption = {
        otherOption: {
          tableType: "model"
        },
        queryOpt: {
          disable: false,
          labelWidth: "68px",
          params: {
            protocolType: "",
            modelName: ""
          },
          page: {
            pageSize: 10,
            pageNum: 1,
            total: 0
          },
          inline: true,
          queryChilds: [
            {
              style: "",
              placeholder: "型号名称",
              clearable: true,
              label: "型号名称",
              type: "input",
              key: "modelName",
              size: "small",
              value: ""
            },
            {
              style: "",
              placeholder: "协议类型",
              clearable: true,
              label: "协议类型",
              type: "select",
              key: "protocolType",
              size: "small",
              value: "",
              options: [
                // {
                //   key: "IOTOS",
                //   label: "iot平台",
                //   value: "IOTOS"
                // },
                // {
                //   key: "ONENET",
                //   label: "ONENET",
                //   value: "ONENET"
                // },
                {
                  key: "OFFICIAL",
                  label: "官方平台",
                  value: "OFFICIAL"
                }
              ],
              optionKey: {
                key: "key",
                label: "label",
                value: "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;
    },
    // 打开设备选择窗口 ——表格
    openTableSelectDialog() {
      this.selectResult = {};
      this.tableSelectOption = {
        otherOption: {
          tableType: "device"
        },
        queryOpt: {
          disable: false,
          labelWidth: "68px",
          params: {
            deviceName: "",
            deviceType: "GATEWAY_CONTROLLER",
            // parentId: '0'
          },
          page: {
            pageSize: 10,
            pageNum: 1,
            total: 0
          },
          inline: true,
          queryChilds: [
            {
              style: "",
              placeholder: "设备名称",
              clearable: true,
              label: "设备名称",
              type: "input",
              key: "deviceName",
              size: "small",
              value: ""
            }
          ]
        },
        tableOpt: {
          loading: false,
          rowKey: "deviceId",
          selection: false,
          maxHeight: "45vh",
          childs: [
            {
              style: "",
              label: "所属型号",
              type: "",
              prop: "modelName",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span"
            },
            {
              style: "",
              label: "设备名称",
              type: "",
              prop: "deviceName",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span"
            },
            {
              style: "",
              label: "设备Key",
              type: "",
              prop: "deviceKey",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span"
            },
            {
              style: "",
              label: "创建时间",
              type: "time",
              prop: "createTime",
              align: "center",
              width: "160",
              "show-overflow-tooltip": false,
              tempType: "span"
            }
          ],
          tableList: {
            type: Array
          }
        },
        tableList: []
      };
      this.selectTableShow = true;
    },
    // 查询回调
    childGetList(data) {
      if (data.otherOption.tableType === "device") {
        this.deviceChildList(data);
      } else if (data.otherOption.tableType === "model") {
        this.modelChildList(data);
      }
    },
    initGetModelList() {
      listModel({
        pageNum: 1,
        pageSize: 99999
      }).then(response => {
        this.queryModelOpt = response.rows;
      });
    },
    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);
        }
      );
    },
    deviceChildList(data) {
      listDevice(Object.assign(data.page, data.param, { selected: 1 })).then(
        response => {
          this.tableSelectOption.tableList = response.rows;
          this.tableSelectOption.queryOpt.page.total = Number(response.total);
        }
      );
    },
    // 根据 型号id 获取 型号详情
    getModelInfoById(modelId) {
      getModel(modelId).then(res => {
        this.$refs.paramWrap.setList(res.data.paramList || []);
      });
    },
    // 点击或者双击数据回调
    returnEvent(data) {
      if (data.type === "dblclick") {
        if (data.otherOption.tableType === "device") {
          this.form.parentId = data.value.deviceId;
          this.form.parentName = data.value.deviceName;
        } else if (data.otherOption.tableType === "model") {
          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 = {};
        if (data.otherOption.tableType === "device") {
          this.selectResult.parentId = data.value.deviceId;
          this.selectResult.parentName = data.value.deviceName;
        } else if (data.otherOption.tableType === "model") {
          this.selectResult.modelId = data.value.modelId;
          this.selectResult.modelName = data.value.modelName;
          this.selectResult.deviceType = data.value.deviceType;
          // this.selectResult.paramList = data.value.paramList;
          this.selectResult.prodKey = data.value.prodKey;
        }
        this.selectResult.tableType = data.otherOption.tableType;
      }
    },
    // 点击确定按钮
    resuleClick() {
      if (this.selectResult.tableType === "device") {
        this.form.parentId = this.selectResult.parentId;
        this.form.parentName = this.selectResult.parentName;
      } else if (this.selectResult.tableType === "model") {
        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.$refs.paramWrap.setList(this.selectResult.paramList || []);
      }
      this.selectTableShow = false;
    },
    deviceTypeChange(val) {
      if (val !== "MINIATURE_BREAKER") {
        this.form.parentId = 0;
        this.form.parentName = "";
      } else if (!val) {
        this.form.parentId = "";
        this.form.parentName = "";
      }
    },
    // 查询设备类型列表
    getDeviceTypeList() {
      listDeviceTypeList().then(response => {
        this.deviceTypeList = response.data;
      });
    },
    /** 查询设备列表 */
    getList() {
      this.loading = true;
      listDevice(this.queryParams).then(response => {
        this.deviceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        modelId: null,
        modelName: "",
        parentName: "",
        parentId: null,
        deviceName: null,
        deviceType: null,
        paramList: [],
        deviceKey: "",
        lineType: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const deviceId = row.deviceId || this.ids;
      const _this = this;
      getDevice(deviceId).then(response => {
        _this.form = response.data;
        _this.open = true;
        _this.title = "修改设备";
        setTimeout(() => {
          _this.$refs.paramWrap.setList(response.data.paramList || []);
        }, 100);
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.paramList = this.$refs.paramWrap.getResult();
          this.form.lineType =
            this.form.deviceType === "MINIATURE_BREAKER"
              ? this.form.lineType
              : undefined;
          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();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const deviceIds = row.deviceId || this.ids;
      this.$confirm("是否删除该选项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return delDevice(deviceIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有设备数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return exportDevice(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        });
    },
    chenking_deviceKey(rule, value, callback) {
      const isExp = /^[A-Z a-z 0-9 _ - $]{0,36}$/;
      if (this.form.deviceKey && !isExp.test(this.form.deviceKey)) {
        callback(new Error("格式不正确(数字，英文字母大小写，36个字符)！"));
      } else {
        callback();
      }
    }
  }
};
</script>

<style lang="scss">
.iot-device {
  .eldialog-wrap {
    .el-dialog__header {
      border-bottom: 1px solid #747373;
    }
    .el-dialog__body {
      padding: 0px;
    }
    .el-form {
      padding: 20px;
      padding-right: 40px;
    }
    .el-dialog__footer {
      height: 60px;
      border-top: 1px solid #747373;
      text-align: right;
      width: 100%;
      padding: 0px;
      padding-top: 15px;
      .el-button + .el-button {
        margin-right: 10px;
      }
      .el-button {
        padding-top: 8px;
      }
    }
    .form-params-wrap {
      height: 100%;
      width: calc(100% + 110px);
      position: relative;
      top: 15px;
      left: -90px;
      max-height: 250px;
      overflow: auto;
      padding: 10px;
      border: 1px solid #009688;
      border-radius: 5px;
    }
  }
  .to-home-wrap2 {
    width: 100px;
    height: 30px;
    position: absolute;
    right: 30px;
    top: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 100;
    color: #656363;
    font-size: 20px;
    cursor: default;
    .el-button--medium.is-circle {
      width: 25px;
      height: 20px;
      padding: 0;
      background: #f26a6a;
      color: #fff;
      font-size: 16px;
      border-radius: 5px;
      height: 30px;
      width: 100%;
      font-size: 14px;
    }
  }
  .to-home-wrap2:hover {
    color: #1890ff;
    font-size: 30px;
  }
}
.form-params-wrap::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 8px; /*高宽分别对应横竖滚动条的尺寸*/
  height: 5px;
}
.form-params-wrap::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius: 10px;
  box-shadow: inset 0 0 5px #c4c4c4;
  background: #dededea6;
}
.form-params-wrap::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
  box-shadow: inset 0 0 5px #f6f6f6;
  border-radius: 10px;
  background: #ffffff;
}
</style>
