<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="SNS编号" title="SNS编号" prop="snsId">
        <el-input v-model="queryParams.snsId" placeholder="请输入SNS编号" clearable @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-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="['manage:product: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="['manage:product:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-upload2" size="mini" @click="handleImport"
          v-hasPermi="['manage:product:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-if="refreshTable" border  v-loading="loading" :data="productList" row-key="id" :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="SNS编号" align="center" prop="snsId" />
      <el-table-column label="归属" align="center" prop="parentName" />
      <el-table-column 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="['manage:product:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-plus" @click="handleAdd(scope.row)"
            v-hasPermi="['manage:product:add']">新增</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['manage:product:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改产品树信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- <el-form-item label="归属" prop="aircraftId" v-if="isAdd">
          <el-select v-model="form.aircraftId" placeholder="请选择机号信息" style="width:100%">
            <el-option v-for="item in aircraftOptions" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>user/profile
        </el-form-item> -->
        <el-form-item label="归属" prop="parentId" v-if="!isParentId">
          <treeselect v-model="form.parentId" :options="productOptions" :normalizer="normalizer" placeholder="请选择父ID" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="SNS编号" prop="snsId">
          <el-input v-model="form.snsId" placeholder="请输入SNS编号" />
        </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>

    <!-- 产品树导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的产品树数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import {
  listProduct,
  getProduct,
  delProduct,
  addProduct,
  updateProduct,
  aircraftListSelect,
} from '@/api/manage/product'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'Product',
  components: {
    Treeselect,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 产品树信息表格数据
      productList: [],
      // 产品树信息树选项
      productOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // // 是否新增
      // isAdd: true,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // // 单机列表
      // aircraftOptions: undefined,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        parentId: null,
        name: null,
        snsId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: '归属不能为空', trigger: 'blur' },
        ],
        aircraftId: [
          { required: true, message: '归属不能为空', trigger: 'blur' },
        ],
      },
      upload: {
        title: '',
        // 是否显示弹出层
        open: false,
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 是否更新已存在数据
        updateSupport: 0,
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/manage/product/import',
      },
    }
  },
  created() {
    this.getList()
  },
  computed: {
		isParentId() {
      return this.form.parentId == 0
    },
  },
  methods: {
    /** 查询产品树信息列表 */
    getList() {
      this.loading = true
      listProduct(this.queryParams).then(response => {
        this.productList = this.handleTree(response.data, 'id', 'parentId')
        this.loading = false
      })
    },
    /** 查询单机信息列表 */
    // getAircraftList() {
    //   aircraftListSelect(this.queryParams).then(response => {
    //     this.aircraftOptions = response.data
    //   })
    // },
    /** 转换产品树信息数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      }
    },
    /** 查询产品树信息下拉树结构 */
    getTreeselect() {
      listProduct().then(response => {
        this.productOptions = []
        // const data = { id: 0, name: '顶级节点', children: [], isDisabled: true }
        this.productOptions = this.handleTree(response.data, 'id')
        // this.productOptions.push(data)
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        parentId: null,
        parentName: null,
        aircraftId: null,
        name: null,
        snsId: null,
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      if (row != null && row.id) {
        this.getTreeselect()
        // this.isAdd = false
        this.form.parentId = row.id
      } else {
        // this.isAdd = true
        this.form.parentId = 0
      }
      this.open = true
      this.title = '添加产品树信息'
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false
      this.isExpandAll = !this.isExpandAll
      this.$nextTick(() => {
        this.refreshTable = true
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      if (row.parentId == 0) {
        this.form.aircraftId = row.aircraftId
        this.form.name = row.name
        this.form.snsId = row.snsId
        this.form.parentId = row.parentId
        this.form.id = row.id
        // this.isAdd = true
        this.open = true
        return
      }
      this.getTreeselect()
      if (row != null) {
        this.form.parentId = row.id
      }
      getProduct(row.id).then(response => {
        this.form = response.data
        // this.isAdd = false
        this.open = true
        this.title = '修改产品树信息'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProduct(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addProduct(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除产品树信息编号为"' + row.id + '"的数据项？')
        .then(function () {
          return delProduct(row.id)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'manage/product/export',
        {
          ...this.queryParams,
        },
        `product_${new Date().getTime()}.xlsx`
      )
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '产品树导入'
      this.upload.open = true
    },
    submitFileForm() {
      this.$refs.upload.submit()
    },
    uploadClose() {
      // 关闭弹窗
      this.upload.open = false
      // 重置上传状态和文件
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      // 重置表单
      this.upload.form = {}
      // this.resetForm("uploadForm");
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      if (response.code !== 200) {
        this.$modal.msgError(response.msg)
        return
      }
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          '</div>',
        '导入结果',
        { dangerouslyUseHTMLString: true }
      )
      this.getList()
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        '/manage/product/importTemplate',
        {},
        `product_template_${new Date().getTime()}.xlsx`
      )
    },
  },
}
</script>
