<template>
  <div class="autocontrol-job-params">
    <el-row :gutter="15">
      <el-col :span="11">
        <span>设备：</span>
        <el-input
          style="width: 80%;"
          :disabled="disabled"
          v-model="form.deviceName"
          placeholder="请输入内容"
          @focus="deviceFocus"
        ></el-input>
      </el-col>
      <el-col :span="11">
        <span>分组：</span>
        <el-select v-model="form.cmdKey" :disabled="disabled" style="width: 85%;" @change="cmdChange" placeholder="请选择">
          <el-option
            v-for="item in cmdListOption"
            :key="item.cmdKey"
            :label="item.cmdName"
            :value="item.cmdKey"
          ></el-option>
        </el-select>
      </el-col>
      <el-col :span="2">
        <el-button
          @click="delThisInfo()"
          v-show="disabled === false"
          :disabled="deleteButtonD"
          type="text"
          icon="el-icon-delete-solid"
          style="
            font-size: 20px;
            margin-top: 0px;
            padding-bottom: 1px;
            color: #f36464;
          "
        ></el-button>
      </el-col>
      <el-col :span="24" v-show="comdlistOption && comdlistOption.length > 0">
        <div class="param-wrap">
          <el-form
            :model="property"
            v-if="comdlistOption && comdlistOption.length > 0"
            ref="loginForm"
            label-width="120px"
            width="100%"
          >
            <el-col
              :span="comdlistOption.length === 1 ? 24:12"
              v-for="paramsItem in comdlistOption"
              :key="paramsItem.funId"
            >
              <el-form-item :label="paramsItem.funName +　'：'" :prop="paramsItem.funKey">
                <el-select
                  :disabled="disabled"
                  style="width: 100%;"
                  v-model="property[paramsItem.funKey]"
                  v-if="paramsItem.funValidType === 'ENUM'"
                  clearable
                >
                  <el-option
                    v-for="(keys, valus) in strtoJson(paramsItem.funObj)"
                    :key="valus"
                    :label="keys"
                    :value="valus"
                  ></el-option>
                </el-select>
                <el-input-number
                  style="width: 100%;"
                  :disabled="disabled"
                  v-model="property[paramsItem.funKey]"
                  v-else-if="paramsItem.funValidType === 'RANGE' && (paramsItem.funDataType === 'FLOAT' || paramsItem.funDataType === 'INT32')"
                  :max="paramsItem.funValMax || 0"
                  :min="paramsItem.funValMin || 0"
                  clearable
                ></el-input-number>

                <el-input-number
                  style="width: 100%;"
                  clearable
                  :disabled="disabled"
                  v-model="property[paramsItem.funKey]"
                  v-else-if="paramsItem.funValidType === 'NOT' && (paramsItem.funDataType === 'FLOAT' || paramsItem.funDataType === 'INT32')"
                ></el-input-number>
                <el-input
                  clearable
                  style="width: 100%;"
                  :disabled="disabled"
                  v-else-if="paramsItem.funDataType === 'TEXT'"
                  v-model="property[paramsItem.funKey]"
                />
              </el-form-item>
            </el-col>
          </el-form>
        </div>
      </el-col>
    </el-row>

    <el-dialog
      title="选择"
      :visible.sync="selectTableShow"
      width="75%"
      top="10vh"
      class="select-table-dialog"
      :close-on-click-modal="false"
      append-to-body
    >
      <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 } from "@/api/iot/device";
import SelectTableWrap from "@/components/SelectTable/index";

import axios from "axios";
import { getToken } from "@/utils/auth";
import { basePlatformUrl } from '@/config/env'
import { getDeviceFunList, getDeviceCmdList } from "@/api/iot/device";


export default {
  name: "DeviceParamWrap",
  components: {
    SelectTableWrap
  },
  props: ["paramsDevcie", "tempIndex", "deleteButtonD", "disabled"],
  data() {
    return {
      tableSelectOption: {},
      selectResult: {},
      selectTableShow: false,
      cmdListOption: [],
      comdlistOption: [],
      cmdId: "",
      property: {},
      farstInput: true,
      form: {
        deviceName: "",
        deviceId: "",
        prodId: "",
        guid: "",
        cmdKey: "",
        property: ""
      }
    };
  },
  watch: {
    property: {
      handler(val, oldVal) {
        if (this.property) {
          this.form.property = JSON.stringify(this.property);
        } else {
          this.form.property = "";
        }
        this.reultEventFu();
      },
      deep: true
    },
    form: {
      handler(val, oldVal) {
        this.reultEventFu();
      },
      deep: true
    }
  },
  created() {
    this.form = this.paramsDevcie;
    if (this.form.prodId) {
      this.farstInput = false;
      this.getCmdList();
    }
  },
  methods: {
    reultEventFu() {
      this.form.guid = this.tempIndex;
      this.$emit("resultEvent", { result: this.form, index: this.tempIndex });
    },
    delThisInfo() {
      if (this.deleteButtonD === true) {
        this.msgError("至少需要一条设备数据！");
      } else {
        this.form.guid = this.tempIndex;
        this.$emit("delInfo", this.tempIndex);
      }
    },
    strtoJson(str) {
      return str ? JSON.parse(str.replace(/\\\"/g, '"')) : {};
    },
    cmdChange(val) {
      for (var i = 0; i < this.cmdListOption.length; i++) {
        if (val === this.cmdListOption[i]["cmdKey"]) {
          this.cmdId = this.cmdListOption[i]["cmdId"];
          this.getcomdlistOption();
          break;
        }
      }
    },
    getcomdlistOption() {
      this.comdlistOption = [];
      const params = {
        deviceId: this.form.deviceId,
        cmdId: this.cmdId,
        cmdType: "2"
      }
      getDeviceFunList(params).then(res => {
          var result = {};
          this.comdlistOption = res.data;
          if (this.farstInput) {
            this.property = {};
            this.comdlistOption.forEach(v => {
              if (!result[v.funKey]) {
                result[v.funKey] = "";
              }
            });
            this.property = result;
          } else {
            this.property = JSON.parse(this.form.property);
            this.farstInput = true;
          }
        });
    },
    // 根据产品id获取分组信息 基础平台
    getCmdList() {
      const params = {
        deviceId: this.form.deviceId,
        cmdId: this.cmdId,
        cmdType: "2"
      }
      getDeviceCmdList(params).then(res => {
          this.cmdListOption = res.data;
          if (this.form.cmdKey) {
            this.cmdChange(this.form.cmdKey);
          }
        });
    },
    deviceFocus() {
      this.openTableSelectDialog();
    },
    // 打开设备选择窗口 ——表格
    openTableSelectDialog() {
      this.selectResult = {};
      this.tableSelectOption = {
        otherOption: {
          tableType: "device"
        },
        queryOpt: {
          disable: false,
          labelWidth: "68px",
          property: {
            deviceName: "",
            modelId: "",
            parentId: 0,
            deviceType: "GATEWAY_CONTROLLER"
          },
          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;
    },
    // 点击或者双击数据回调
    returnEvent(data) {
      if (data.type === "dblclick") {
        this.form.deviceName = data.value.deviceName;
        this.form.deviceId = data.value.deviceId;
        this.form.prodId = data.value.prodKey;
        this.form.deviceKey = data.value.deviceKey
        this.selectTableShow = false;
        this.form.cmdKey = "";
        this.property = {};
        this.comdlistOption = [];
        this.getCmdList();
      } else if (data.type === "click") {
        this.selectResult = {};
        this.selectResult.deviceId = data.value.deviceId;
        this.selectResult.deviceName = data.value.deviceName;
        this.selectResult.prodId = data.value.prodKey;
        this.selectResult.deviceKey = data.value.deviceKey
      }
    },
    // 点击确定按钮
    resuleClick() {
      this.form.deviceName = this.selectResult.deviceName;
      this.form.deviceId = this.selectResult.deviceId;
      this.form.prodId = this.selectResult.prodKey;
      this.form.deviceKey = this.selectResult.deviceKey
      this.selectTableShow = false;
      this.form.cmdKey = "";
      this.property = {};
      this.comdlistOption = [];
      this.getCmdList();
    },
    // 查询回调
    childGetList(data) {
      this.deviceChildList(data);
    },
    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);
        }
      );
    }
  }
};
</script>
<style lang="scss">
.autocontrol-job-params {
  padding: 10px 5px;
  background-color: #e4e3e3;
  margin-top: 5px;
  .param-wrap {
    height: 100%;
    width: 100%;
    max-height: 200px;
    overflow: auto;
    /* border: 1px solid red; */
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-pack: start;
    -ms-flex-pack: start;
    justify-content: flex-start;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
    padding: 10px;
    margin-top: 10px;
    background: #99e4f59e;
    box-shadow: 0px 0px 4px #6a6c6d9e;
  }
}
</style>
