<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-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:ota:add']"
          >新增</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="['system:ota:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:ota:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row> -->

    <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="150" prop="modelName" />
      <el-table-column
        label="固件版本"
        align="center"
        width="120"
        prop="otaVersion"
      />
      <el-table-column
        label="固件大小"
        align="center"
        width="120"
        prop="otaSize"
      />
      <el-table-column label="升级地址" align="left" prop="otaUrl">
        <template slot-scope="scope">
          <span
            style="
              max-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
            v-if="scope.row.otaUrl"
            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="
              max-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
            v-if="scope.row.txtUrl"
            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"
      >
      <template slot-scope="scope">
        <span class="lay-table-textarea" :title="scope.row.otaInfo">
          {{ scope.row.otaInfo }}
        </span>
      </template>
      </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-hasPermi="['system:ota:edit']"
            >修改</el-button
          >
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:ota: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>
      <dialog-template @close="open = false"  :title="title" :visible="open"  width="500px">
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          slot="dialog-center"
          label-width="100px"
        >
          <el-form-item label="型号:" prop="modelName">
            <el-input
              v-model="form.modelName"
              placeholder="点击选择型号"
              @focus="openModelTableSelectDialog()"
            />
          </el-form-item>
          <el-form-item label="固件版本:" prop="otaVersion">
            <el-input v-model="form.otaVersion" placeholder="请输入固件版本" />
          </el-form-item>

          <el-form-item label="升级地址:" prop="otaUrl">
            <el-input v-model="form.otaUrl" placeholder="请输入固件升级地址" />
          </el-form-item>

          <el-form-item label="文件地址:" prop="txtUrl">
            <el-tabs v-model="isFileUpload">
              <el-tab-pane label="文本输入" name="input">
                <el-input
                  v-show="isFileUpload === 'input'"
                  v-model="form.txtUrl"
                  placeholder="请输入文件地址"
                />
              </el-tab-pane>
              <el-tab-pane label="文件上传" name="fileUpload">
                <el-upload
                  ref="upload"
                  :show-file-list="false"
                  :http-request="uploud"
                  action
                  drag
                >
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">
                    将文件拖到此处，或
                    <em>点击上传</em>
                  </div>
                  <!-- <div class="el-upload__tip" slot="tip">
                    只能上传jpg/png文件，且不超过500kb
                  </div> -->
                </el-upload>
              </el-tab-pane>
            </el-tabs>
          </el-form-item>

          <el-form-item label="固件大小:" prop="otaSize">
            <el-input v-model="form.otaSize" placeholder="请输入固件大小" />
          </el-form-item>

          <el-form-item label="升级信息:" prop="otaInfo">
            <el-input
              v-model="form.otaInfo"
              type="textarea"
              :rows="4"
              maxlength="99"
              placeholder="请输入固件升级信息"
            />
          </el-form-item>
        </el-form>

        <div slot="dialog-footer">
          <el-button type="primary" size="mini" @click="submitForm"
            >确 定</el-button
          >
          <el-button size="mini" @click="cancel">取 消</el-button>
        </div>
      </dialog-template>

      <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>
  </div>
</template>

<script>
import {
  listOta,
  getOta,
  delOta,
  addOta,
  updateOta,
  exportOta,
} from "@/api/iot/deviceOta";
import DialogTemplate from "@/components/DialogTemplate";
import SelectTableWrap from "@/components/SelectTable/index";
import { listModel, getModel } from "@/api/iot/model";
import { getToken } from "@/utils/auth";
import { uploadFile } from "@/api/file";

export default {
  name: "Ota",
  components: {
    DialogTemplate,
    SelectTableWrap,
  },
  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: {},
      // 表单校验
      rules: {
        modelName: [
          {
            required: true,
            validator: this.chenking_modelName,
            trigger: "change",
          },
        ],
        otaVersion: [
          { required: true, message: "版本不能为空", trigger: "blur" },
        ],
        otaUrl: [
          { required: true, message: " 升级地址不能为空", trigger: "blur" },
        ],
        txtUrl: [
          { required: true, message: " 文件地址不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    copyOnClick(val) {
      let self = this;
      this.$copyText(val).then(
        function () {
          self.$message({
            message: "复制成功",
            type: "success",
          });
        },
        function () {
          self.$message.error("复制失败");
        }
      );
    },
    chenking_modelName(rule, value, callback) {
      if (!this.form.modelId) {
        callback(new Error("型号不能为空，请选择！"));
      } else {
        callback();
      }
    },
    sortChange(column) {
      const sort = {
        isAsc: column.order === "descending" ? "desc" : "asc",
        orderByColumn: column.prop,
      };
      this.queryParams = Object.assign(this.queryParams, sort);
      this.handleQuery();
    },
    uploud(file) {
      console.log(file);
      var formData = new FormData();
      var that = this;
      formData.append("file", file.file);
      uploadFile(formData)
        .then((response) => {
          if (response.code === 200) {
            that.form.otaSize = file.file.size;
            that.form.txtUrl = response.url;
            that.isFileUpload = "input";
            that.$forceUpdate();
          }
        })
        .catch((e) => {
          console.log(e);
        });
    },
    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;
    },
    // 打开厂商选择窗口 ——表格
    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;
    },
    childGetList(data) {
      this.modelChildList(data);
    },
    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);
        }
      );
    },
    // 点击或者双击数据回调
    returnEvent(data) {
      if (data.type === "dblclick") {
        this.form.modelId = data.value.modelId;
        this.form.modelName = data.value.modelName;
        this.$refs.form.validateField("modelId");
        this.selectTableShow = false;
      } else if (data.type === "click") {
        this.selectResult = {};
        this.selectResult.modelId = data.value.modelId;
        this.selectResult.modelName = data.value.modelName;
      }
    },
    // 点击确定按钮
    resuleClick() {
      this.form.modelId = this.selectResult.modelId;
      this.form.modelName = this.selectResult.modelName;
      this.$refs.form.validateField("modelId");
      this.selectTableShow = false;
    },

    indexFormatter(val) {
      return (
        val + 1 + (this.queryParams.pageNum - 1) * this.queryParams.pageSize
      );
    },
    /** 查询固件版本列表 */
    getList() {
      this.loading = true;
      listOta(this.queryParams).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;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加固件版本";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const otaId = row.otaId || this.ids;
      getOta(otaId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改固件版本";
      });
    },
    /** 提交按钮 */
    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>
