<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="固件版本" prop="otaVersion">
        <el-input
          v-model="queryParams.otaVersion"
          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-table
      v-loading="loading"
      :data="otaList"
      :default-sort="{ prop: 'createTime', order: 'descending' }"
      @sort-change="sortChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="index"
        label="序号"
        align="center"
        :index="indexFormatter"
        width="80px"
      ></el-table-column>
      <el-table-column label="型号" align="laft" width="200" prop="modelName" />
      <el-table-column
        label="固件版本"
        align="center"
        width="160"
        prop="otaVersion"
      />
      <el-table-column
        label="固件大小"
        align="center"
        width="160"
        prop="otaSize"
      />
      <el-table-column label="升级地址" align="left" prop="otaUrl">
        <template slot-scope="scope">
          <span
            style="
              width: calc(100% - 60px);
              white-space: nowrap;
              display: inline-block;
              overflow: hidden;
              text-overflow: ellipsis;
              line-height: 30px;
              height: 20px;
            "
            >{{ scope.row.otaUrl }}</span
          >
          <!-- <span
            style="
              cursor: default;
              position: relative;
              right: -10px;
              color: #3a8ee6;
            "
            @click="copyOnClick(scope.row.otaUrl)"
            >复制</span
          > -->
        </template>
      </el-table-column>
      <el-table-column label="文件地址" align="left" prop="txtUrl">
        <template slot-scope="scope">
          <span
            style="
              width: calc(100% - 60px);
              white-space: nowrap;
              display: inline-block;
              overflow: hidden;
              text-overflow: ellipsis;
              height: 20px;
              line-height: 30px;
            "
            >{{ scope.row.txtUrl }}</span
          >
          <!-- <span
            style="
              cursor: default;
              position: relative;
              right: -10px;
              color: #3a8ee6;
            "
            @click="copyOnClick(scope.row.txtUrl)"
            >复制</span
          > -->
        </template>
      </el-table-column>
      <el-table-column
        label="升级信息"
        align="left"
        prop="otaInfo"
      ></el-table-column>
      <el-table-column
        label=" 创建时间"
        align="center"
        prop="createTime"
        sortable="custom"
        width="150px"
      />
      <el-table-column
        label="操作"
        width="150"
        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-show="deviceInfo['otaVersion'] !== scope.row.otaVersion"
            >升级固件</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>
</template>

<script>
import {
  listOta,
  upgradeOta
} from "@/api/iot/deviceOta";
import DialogTemplate from "@/components/DialogTemplate";
import { listModel, getModel } from "@/api/iot/model";
import { uploadFile } from "@/api/file";

export default {
  name: "Ota",
  props: {
    deviceInfo: {
      type: Object,
      default: {}
    }
  },
  components: {
    DialogTemplate,
  },
  data() {
    return {
      isFileUpload: "input",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 固件版本表格数据
      otaList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        modelId: null,
        otaVersion: null,
        otaSize: null,
        otaUrl: null,
        txtUrl: null,
        otaInfo: null,
      },
      selectTableShow: false,
      tableSelectOption: {},
      selectResult: {},
      // 表单参数
      form: {},
    };
  },
  created() {
    this.getList();
  },
  methods: {
    copyOnClick(val) {
      let self = this;
      this.$copyText(val).then(
        function () {
          self.$message({
            message: "复制成功",
            type: "success",
          });
        },
        function () {
          self.$message.error("复制失败");
        }
      );
    },
    sortChange(column) {
      const sort = {
        isAsc: column.order === "descending" ? "desc" : "asc",
        orderByColumn: column.prop,
      };
      this.queryParams = Object.assign(this.queryParams, sort);
      this.handleQuery();
    },
    beforeAvatarUpload(file) {
      const isJPG = this.fileType.indexOf(file.type) >= 0;
      const isLt2M = file.size < this.fileSize;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isLt2M;
    },

    indexFormatter(val) {
      return (
        val + 1 + (this.queryParams.pageNum - 1) * this.queryParams.pageSize
      );
    },
    /** 查询固件版本列表 */
    getList() {
      this.loading = true;
      listOta(Object.assign(this.queryParams, {
          modelId: this.deviceInfo.modelId
      })).then((response) => {
        this.otaList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        otaId: null,
        modelId: null,
        otaVersion: null,
        otaSize: null,
        otaUrl: null,
        txtUrl: null,
        otaInfo: null,
        createId: null,
        createTime: null,
        updateId: null,
        updateTime: null,
        modelName: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.otaId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      let that = this
      this.$confirm("升级固件操作执行中，可能由 设备异常 等问题导致升级不成功，是否升级该固件?", "升级固件", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "success",
      })
        .then(function () {
          return upgradeOta({
            'otaId': row.otaId,
            'deviceId': that.deviceInfo.deviceId
          });
        })
        .then(() => {
          this.$emit('updateInfo')
          this.getList();
          // this.msgSuccess("固件升级成功");
          this.$message({
            message: '升级固件已经提交，固件正在升级中（过程中有可能由 异常 等问题导致升级不成功！）',
            type: 'success'
          });
        });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.otaId != null) {
            updateOta(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOta(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const otaIds = row.otaId || this.ids;
      this.$confirm("是否删除该选项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delOta(otaIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有固件版本数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportOta(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
  },
};
</script>
