<template>
  <div class="app-container iot-model">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <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="产品PK" prop="prodKey">
        <el-input
          v-model="queryParams.prodKey"
          placeholder="产品PK"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="协议类型" prop="protocolType">
        <el-select
          v-model="queryParams.protocolType"
          @change="handleQuery"
          placeholder="请选择协议类型"
          clearable
          size="small"
        >
          <el-option
            :label="keys"
            :value="vals"
            v-for="(keys, vals) in protocolTypeOpt"
            :key="keys"
          />
        </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:model:add']"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="modelList"
      :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"
        width="200px"
        prop="modelName"
      />
      <el-table-column
        label="厂商名称"
        align="left"
        width="200px"
        prop="vendorName"
      />
      <el-table-column
        label="产品PK"
        align="left"
        width="200px"
        prop="prodKey"
      />
      <el-table-column label="产品密钥" align="left" prop="prodSecret">
        <template slot-scope="scope">
          <span class="lay-table-textarea" :title="scope.row.prodSecret">
            {{ scope.row.prodSecret }}
          </span>
        </template>
      </el-table-column>

      <el-table-column
        label="设备类型"
        align="center"
        prop="deviceType"
        width="120px"
      >
        <template slot-scope="scope">
          <span v-text="deviceTypeList[scope.row.deviceType]"></span>
        </template>
      </el-table-column>

      <el-table-column
        label="协议类型"
        align="center"
        prop="protocolType"
        width="120px"
      >
        <template slot-scope="scope">
          <span v-text="protocolTypeOpt[scope.row.protocolType]"></span>
        </template>
      </el-table-column>

      <el-table-column
        label="设备状态"
        align="center"
        prop="modelStatus"
        width="100px"
      >
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.modelStatus === '0'"
            >启用</el-tag
          >
          <el-tag type="danger" v-else>禁用</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        label=" 创建时间"
        align="center"
        sortable="custom"
        prop="createTime"
        width="150px"
      />
      <el-table-column
        width="160px"
        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="['iot:model:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iot:model: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="1000px"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="厂商：" prop="vendorId">
              <el-input
                v-model="form.vendorName"
                placeholder="点击选择厂商"
                @focus="openTableSelectDialog()"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="协议类型：" prop="protocolType">
              <el-select
                v-model="form.protocolType"
                style="width: 100%"
                placeholder="请选择协议类型"
                size="small"
              >
                <el-option
                  :label="keys"
                  :value="vals"
                  v-for="(keys, vals) in protocolTypeOpt"
                  :key="vals"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品PK：" prop="prodKey">
              <el-input
                v-if="form.protocolType === 'OFFICIAL'"
                placeholder="请填写产品PK"
                v-model="form.prodKey"
              ></el-input>
              <el-input
                v-else
                v-model="form.prodKey"
                placeholder="点击选择产品"
                @focus="openProductTableSelectDialog()"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="型号名称：" prop="modelName">
              <el-input v-model="form.modelName" placeholder="请输入型号名称" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="产品json："
              prop="prodJson"
              v-if="form.protocolType === 'OFFICIAL'"
            >
              <attribute-view
                v-if="open"
                :arttributeList="form.prodJson"
                :groupList="form.remark"
                @handleEvent="handleViewEvent"
                ref="attributeref"
              ></attribute-view>
            </el-form-item>
          </el-col>

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

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

    <dialog-template
      :title="componentTitle"
      @close="
        () => {
          AttributeViewShow = false;
        }
      "
      :visible="AttributeViewShow"
      width="750px"
    >
      <component
        v-if="AttributeViewShow"
        :is="componectVal"
        :tempType="childOpt.type"
        :paramIdx="childOpt.paramIdx"
        :other="{
          action: '',
          prodPK: form.prodKey,
          cmdKey: '',
        }"
        :paramsList="functionList"
        ref="componentref"
        @ok="compEventOk"
        slot="dialog-center"
      ></component>

      <div slot="dialog-footer">
        <el-button type="primary" size="mini" @click="submitAttribute"
          >确 定</el-button
        >
        <el-button
          size="mini"
          @click="
            () => {
              AttributeViewShow = false;
            }
          "
          >取 消</el-button
        >
      </div>
    </dialog-template>
  </div>
</template>

<script>
import {
  listModel,
  getModel,
  delModel,
  addModel,
  updateModel,
  exportModel,
  listProductList,
  listModelType,
} from "@/api/iot/model";
import { listVendor } from "@/api/iot/vendor";
import { listDeviceTypeList } from "@/api/iot/device";
import SelectTableWrap from "@/components/SelectTable/index";
import ParamWrap from "@/components/ParamWrap/deviceParam";
import AttributeView from "@/views/profile/attribute/index";

import DialogTemplate from "@/components/DialogTemplate";

import attributeForm from "@/views/profile/attribute/attributeForm";
import groupForm from "@/views/profile/attribute/groupForm";
import paramsJson from "@/views/profile/attribute/paramsJson";

const deviceStartsOpt = {
  0: "禁用",
  1: "启用",
};

export default {
  name: "Model",
  components: {
    SelectTableWrap,
    ParamWrap,
    AttributeView,
    DialogTemplate,
    attributeForm,
    groupForm,
    paramsJson,
  },
  data() {
    return {
      componectVal: "attributeForm",
      childOpt: {
        type: "add",
        paramIdx: 0,
      },
      protocolTypeOpt: {},
      AttributeViewShow: false,
      AttributeFormViewShow: false,
      selectTableShow: false,
      tableSelectOption: {},
      selectResult: {},
      deviceStartsOpt,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 型号表格数据
      modelList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        vendorId: null,
        modelName: null,
        modelCode: null,
        prodKey: null,
        prodSecret: null,
        protocolType: null,
        orderByColumn: "createTime",
        isAsc: "desc",
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        vendorId: [
          { required: true, message: "厂商不能为空", trigger: "change" },
        ],
        prodKey: [
          { required: true, message: "产品PK不能为空", trigger: "change" },
        ],
        modelName: [
          { required: true, message: "型号名称不能为空", trigger: "blur" },
        ],
        deviceType: [
          { required: true, message: "设备类型不能为空", trigger: "blur" },
        ],
      },
      functionList: [],
      deviceTypeList: {},
      componentTitle: "",
    };
  },
  created() {
    this.getModelTypeList();
    this.getDeviceTypeList();
    this.getList();
  },
  methods: {
    handleViewEvent(data) {
      console.log(data);
      this.componentTitle = data.title;
      (this.childOpt.type = data.type),
        (this.childOpt.paramIdx = data.paramIdx);
      this.AttributeViewShow = true;
      this.functionList = JSON.parse(
        JSON.stringify(this.$store.getters.attributeList)
      );
      this.componectVal = data.component;
    },
    submitAttribute() {
      if (this.childOpt.type === "param") {
        this.AttributeViewShow = false;
        return;
      }
      if (this.$refs.componentref) {
        this.$refs.componentref.submitForm();
      }
    },
    compEventOk() {
      //执行
      this.AttributeViewShow = false;
      this.$forceUpdate();
      this.$refs.attributeref.forceUpdate(this.componectVal);
    },
    getModelTypeList() {
      listModelType().then((res) => {
        this.protocolTypeOpt = res.data;
      });
    },
    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
      );
    },
    // 查询设备类型列表
    getDeviceTypeList() {
      listDeviceTypeList().then((response) => {
        this.deviceTypeList = response.data;
      });
    },
    openProductTableSelectDialog() {
      this.selectResult = {};
      this.tableSelectOption = {
        otherOption: {
          tableType: "product",
        },
        queryOpt: {
          disable: false,
          labelWidth: "68px",
          params: {
            protocolType: this.form.protocolType,
          },
          page: {
            pageSize: 10,
            pageNum: 1,
            total: 0,
          },
          inline: true,
          queryChilds: [],
        },
        tableOpt: {
          loading: false,
          rowKey: "prodId",
          selection: false,
          maxHeight: "45vh",
          childs: [
            {
              style: "",
              label: "产品名称",
              type: "",
              prop: "prodName",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span",
            },
            {
              style: "",
              label: "产品PK",
              type: "",
              prop: "prodId",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span",
            },
          ],
          tableList: {
            type: Array,
          },
        },
        tableList: [],
      };
      this.selectTableShow = true;
    },
    // 打开厂商选择窗口 ——表格
    openTableSelectDialog() {
      this.selectResult = {};
      this.tableSelectOption = {
        otherOption: {
          tableType: "vendor",
        },
        queryOpt: {
          disable: false,
          labelWidth: "68px",
          params: {
            vendorName: "",
            vendorAddress: "",
            vendorContact: "",
          },
          page: {
            pageSize: 10,
            pageNum: 1,
            total: 0,
          },
          inline: true,
          queryChilds: [
            {
              style: "",
              placeholder: "厂商名称",
              clearable: true,
              label: "厂商名称",
              type: "input",
              key: "vendorName",
              size: "small",
              value: "",
            },
            {
              style: "",
              placeholder: "厂商地址",
              clearable: true,
              label: "厂商地址",
              type: "input",
              key: "vendorAddress",
              size: "small",
              value: "",
            },
            {
              style: "",
              placeholder: "联系方式",
              clearable: true,
              label: "联系方式",
              type: "input",
              key: "vendorContact",
              size: "small",
              value: "",
            },
          ],
        },
        tableOpt: {
          loading: false,
          rowKey: "deviceId",
          selection: false,
          maxHeight: "45vh",
          childs: [
            {
              style: "",
              label: "厂商名称",
              type: "",
              prop: "vendorName",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span",
            },
            {
              style: "",
              label: " 联系方式",
              type: "",
              prop: "vendorContact",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span",
            },
            {
              style: "",
              label: "厂商地址",
              type: "",
              prop: "vendorAddress",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span",
            },
          ],
          tableList: {
            type: Array,
          },
        },
        tableList: [],
      };
      this.selectTableShow = true;
    },
    // 查询回调
    childGetList(data) {
      if (data.otherOption.tableType === "vendor") {
        this.vendorChildList(data);
      } else if (data.otherOption.tableType === "product") {
        this.productChildList(data);
      }
    },
    productChildList(data) {
      listProductList(
        Object.assign(data.page, data.param, { selected: 1 })
      ).then((response) => {
        this.tableSelectOption.tableList = response.data;
        // this.tableSelectOption.queryOpt.page.total = Number(response.total);
      });
    },
    vendorChildList(data) {
      listVendor(Object.assign(data.page, data.param, { selected: 1 })).then(
        (response) => {
          this.tableSelectOption.tableList = response.rows;
          this.tableSelectOption.queryOpt.page.total = Number(response.total);
        }
      );
    },
    // 点击或者双击数据回调
    returnEvent(data) {
      this.selectResult = {};
      if (data.type === "dblclick") {
        if (data.otherOption.tableType === "vendor") {
          this.form.vendorId = data.value.vendorId;
          this.form.vendorName = data.value.vendorName;
        } else if (data.otherOption.tableType === "product") {
          this.form.prodKey = data.value.prodId;
          this.form.prodSecret = data.value.prodSecret;
        }
        this.selectTableShow = false;
      } else if (data.type === "click") {
        if (data.otherOption.tableType === "vendor") {
          this.selectResult.vendorId = data.value.vendorId;
          this.selectResult.vendorName = data.value.vendorName;
        } else if (data.otherOption.tableType === "product") {
          this.selectResult.prodKey = data.value.prodId;
          this.selectResult.prodSecret = data.value.prodSecret;
        }
        this.selectResult.tableType = data.otherOption.tableType;
      }
    },
    // 点击确定按钮
    resuleClick() {
      if (this.selectResult.tableType === "vendor") {
        this.form.vendorId = this.selectResult.vendorId;
        this.form.vendorName = this.selectResult.vendorName;
      } else if (this.selectResult.tableType === "product") {
        this.form.prodKey = this.selectResult.prodKey;
        this.form.prodSecret = this.selectResult.prodSecret;
      }
      this.selectTableShow = false;
    },
    /** 查询型号列表 */
    getList() {
      this.loading = true;
      listModel(this.queryParams).then((response) => {
        this.modelList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        vendorId: null,
        modelName: null,
        vendorName: "",
        prodKey: "",
        deviceType: "",
        paramList: [],
        protocolType: "OFFICIAL",
        prodJson: "",
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.modelId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加型号";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const modelId = row.modelId || this.ids;
      const _this = this;
      getModel(modelId).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) {
          if (this.form.protocolType === "OFFICIAL") {
            let attrList = [];
            if (
              this.$store.getters.attributeList &&
              this.$store.getters.attributeList.length > 0
            ) {
              attrList = this.$store.getters.attributeList.map((v) => {
                v["sourceId"] = this.form.prodKey;
                return v;
              });
            }

            let groupList = [];
            if (
              this.$store.getters.groupList &&
              this.$store.getters.groupList.length > 0
            ) {
              groupList = this.$store.getters.groupList.map((v) => {
                v["sourceId"] = this.form.prodKey;
                return v;
              });
            }
            console.log(groupList, attrList);
            this.form.prodJson = JSON.stringify(attrList) || null;
            this.form.remark = JSON.stringify(groupList) || null;
          }

          this.form.paramList = this.$refs.paramWrap.getResult();
          if (this.form.modelId != null) {
            updateModel(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addModel(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const modelIds = row.modelId || this.ids;
      this.$confirm("是否删除该选项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delModel(modelIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有型号数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportModel(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
  },
};
</script>
<style lang="scss">
.iot-model {
  .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;
    }
  }
}
.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>
