<template>
  <section class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="固件名称">
        <el-input v-model="queryParams.fileName" placeholder="请输入固件名称" clearable size="small" style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产品">
        <el-select v-model="queryParams.productId" clearable placeholder="请选择" @change="queryProductIdChange">
          <el-option v-for="item in queryProductSelectList" :key="item.id" :label="item.productName" :value="item.productId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="节点">
        <el-select v-model="queryParams.nodeId" clearable placeholder="请选择">
          <el-option v-for="item in queryNodeSelectList" :key="item.id" :label="item.nodeName" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="客户" prop="userId">
        <el-select v-model="queryParams.userId" clearable placeholder="请选择" @change="queryUserIdChange">
          <el-option v-for="item in queryUserSelectList" :key="item.id" :label="item.nickName" :value="item.userId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目" prop="projectId">
        <el-select v-model="queryParams.projectId" clearable placeholder="请选择">
          <el-option v-for="item in queryProjectSelectList" :key="item.id" :label="item.projectName" :value="item.projectId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" 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 size="mini" type="primary" icon="el-icon-plus" @click="handleAdd" v-hasPermi="['system:management:add']">增加
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['monitor:management:remove']">批量删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table :data="tableData" row-key="id" :tree-props="tableTreeProps" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center">
      </el-table-column>
      <el-table-column prop="version" align="center" label="固件版本号">
        <!-- <template slot-scope="scope">
          <el-popover placement="right" title="标题" width="200" trigger="hover">
            <el-table :data="tableData">
              <el-table-column prop="status" align="center" label="状态">
              </el-table-column>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template>
                  <el-switch v-model="typeValue" active-color="#13ce66" inactive-color="#ff4949">
                  </el-switch>
                </template>
              </el-table-column>
            </el-table>
            <el-button slot="reference">{{scope.row.version}}</el-button>
          </el-popover>
        </template> -->
      </el-table-column>
      <el-table-column prop="fileName" align="center" label="固件名称">
      </el-table-column>
      <el-table-column prop="productName" align="center" label="产品名称">
      </el-table-column>
      <el-table-column prop="nodeName" align="center" label="节点名称">
      </el-table-column>
      <el-table-column prop="userName" align="center" label="客户名称">
      </el-table-column>
      <el-table-column prop="projectName" align="center" label="项目名称">
      </el-table-column>
      <el-table-column align="center" label="状态">
        <template slot-scope="scope">{{scope.row.status == 1 ? '启用' : '禁用' }}</template>
      </el-table-column>
      <el-table-column prop="remark" align="center" label="备注">
      </el-table-column>
      <el-table-column min-width="150" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-show="scope.row.status == 2" size="mini" type="text" icon="el-icon-open" @click="enable(scope.row)" v-hasPermi="['system:management:enable']">
            启用
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:management:edit']">
            修改
          </el-button>
          <el-button v-show="scope.row.status == 2"  class="text-danger" size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:management: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 :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="产品" prop="productId">
          <el-select :disabled="!!form.id" v-model="form.productId" clearable placeholder="请选择" @change="productIdChange">
            <el-option v-for="item in productSelectList" :key="item.id" :label="item.productName" :value="item.productId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="节点" prop="nodeId">
          <el-select :disabled="!!form.id" v-model="form.nodeId" clearable placeholder="请选择">
            <el-option v-for="item in nodeSelectList" :key="item.id" :label="item.nodeName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户" prop="userId">
          <el-select :disabled="!!form.id" v-model="form.userId" clearable placeholder="请选择" @change="userIdChange">
            <el-option v-for="item in userSelectList" :key="item.id" :label="item.nickName" :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目" prop="projectId">
          <el-select :disabled="!!form.id" v-model="form.projectId" clearable placeholder="请选择">
            <el-option v-for="item in projectSelectList" :key="item.id" :label="item.projectName" :value="item.projectId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传文件" prop="version">
          <el-upload ref="upload" :limit="1" :show-file-list="false" accept=".bin" :headers="upload.headers" :action="upload.url"
            :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              <el-input v-model="form.fileName" disabled placeholder="文件名称" />
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="固件版本号" prop="version">
          <el-input v-model="form.version" placeholder="请输入固件版本号" />
        </el-form-item>
        <el-form-item label="硬件版本号" prop="fwVersion">
          <el-input v-model="form.fwVersion" placeholder="请输入硬件版本号" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import { getToken } from "@/utils/auth";
import { list, get, add, update, del, enable } from "@/api/firmware/management";
import { select as productSelect } from "@/api/hardware/product";
import { productNodeList,productNodeSelect } from "@/api/hardware/productNode";
import { select as projectSelect } from "@/api/hardware/project";
import { userSelect } from "@/api/system/user";
export default {
  name: "FirmwareList",
  data () {
    return {
      // 产品下拉列表
      queryProductSelectList: [],
      queryNodeSelectList: [],
      queryUserSelectList: [],
      queryProjectSelectList: [],
      productSelectList: [],
      nodeSelectList: [],
      userSelectList: [],
      projectSelectList: [],
      // 固件上传
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/minio/uploadFirmwareFile"
      },
      // visible: false,
      // typeValue:true,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      tableTreeProps: {children: 'childList', hasChildren: 'hasChildren'},
      // 表格数据
      tableData: [],
      rules: {
        version: [
          { required: true, message: "固件版本号不能为空", trigger: "blur" },
        ],
        fwVersion: [
          { required: true, message: "硬件版本号不能为空", trigger: "blur" },
        ],
        fileName: [
          { required: true, message: "必须上传文件", trigger: "blur" },
        ],
        productId: [
          { required: true, message: "产品不能为空", trigger: "blur" },
        ],
        nodeId: [
          { required: true, message: "节点不能为空", trigger: "blur" },
        ],
        userId: [
          { required: true, message: "客户不能为空", trigger: "blur" },
        ],
        projectId: [
          { required: true, message: "项目不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created () {
    productSelect().then(({ code, msg, select }) => {
      if (code == 200) {
        this.queryProductSelectList = select;
        this.productSelectList = select;
      } else {
        this.msgError(msg);
      }
    })
    userSelect().then(({ code, msg, select }) => {
      if (code == 200) {
        this.queryUserSelectList = select;
        this.userSelectList = select;
      } else {
        this.msgError(msg);
      }
    })
    this.getList();
  },
  methods: {
    queryProductIdChange (productId) {
      delete this.queryParams.nodeId;
      productNodeSelect({ productId }).then(({ code, msg, select }) => {
        if (code == 200) {
          this.queryNodeSelectList = select;
        } else {
          this.msgError(msg);
        }
      })
    },
    productIdChange (productId) {
      delete this.form.nodeId;
      productNodeSelect({ productId }).then(({ code, msg, select }) => {
        if (code == 200) {
          this.nodeSelectList = select;
        } else {
          this.msgError(msg);
        }
      })
    },
    queryUserIdChange (userId) {
      delete this.queryParams.projectId;
      projectSelect({ userId }).then(({ code, msg, select }) => {
        if (code == 200) {
          this.queryProjectSelectList = select;
        } else {
          this.msgError(msg);
        }
      })
    },
    userIdChange (userId) {
      delete this.form.projectId;
      projectSelect({ userId }).then(({ code, msg, select }) => {
        if (code == 200) {
          this.projectSelectList = select;
        } else {
          this.msgError(msg);
        }
      })
    },
    // 文件上传中处理
    handleFileUploadProgress (event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess (res, file, fileList) {
      if (res.code == 200) {
        this.msgSuccess(res.msg);
        let { fileName, length, url, crc } = res;
        this.form = Object.assign({}, this.form, { fileName, length, filePath: url, crcCode: crc });
      } else {
        this.msgError(res.msg);
      }
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 取消按钮
    cancel () {
      this.open = false;
    },
    // 表单重置
    reset () {
      this.form = {
        version: "",
        fileName: ""
      };
      this.resetForm("form");
    },
    // 获取产品数据列表
    getList () {
      list(this.queryParams).then((response) => {
        this.tableData = response.rows;
        this.total = response.total;
      });
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "添加固件";
    },
    // 启用固件
    enable(row) {
      enable(row.id).then(({code,msg})=> {
        if (200 == code) {
          this.msgSuccess(msg);
          this.getList();
        } else {
          this.msgError(msg);
        }
      })
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      this.productIdChange(row.productId);
      this.userIdChange(row.userId);
      this.form = Object.assign({}, row);
      this.open = true;
      this.title = "修改固件";
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // debugger
          if (this.form.id != undefined) {
            update(this.form).then((res) => {
              if (200 == res.code) {
                this.msgSuccess(this.title + "成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(res.msg);
              }
            });
          } else {
            add(this.form).then((res) => {
              if (200 == res.code) {
                this.msgSuccess(this.title + "成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(res.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = row.id || this.ids;
      this.$confirm("是否确认删除?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return del(ids);
        })
        .catch(() => { })
        .then((res) => {
          if (200 == res.code) {
            this.getList();
            this.msgSuccess("删除成功");
          } else {
            this.msgError(res.msg);
          }
        })
        .catch((res) => { });
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map((item) => item.id);
      this.multiple = !selection.length;
    },
  },
};
</script>

<style>
</style>