<template>
  <div class="bbsl-common-page">
    <div class="bbsl-table-search">
      <el-form ref="searchForm" v-model="queryParam.querys" :inline="true">
        <el-form-item label="侦察情报：">
          <el-input
            v-model="queryParam.querys[0].value"
            clearable
            maxlength="128"
            placeholder="请输入侦察情报"
          >
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" type="primary" @click="handleSearch"
            >搜索
          </el-button>
          <el-button icon="el-icon-refresh" @click="resetSearch">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="page-content">
      <div class="tree-container">
        <tree-side
          ref="treeSide"
          :default-expand-all="false"
          :defaultProps="{children: 'children', label: 'name'}"
          :treeData="treeData"
          isDeselect
          @currentChange="currentChange"
        ></tree-side>
      </div>
      <div ref="contentPanel" class="bbsl-table-content">
        <div ref="btnPanel" class="bbsl-btn-content">
          <el-button
            v-charge
            icon="el-icon-plus"
            type="success"
            @click="showDialog('addEdit')"
          >
            新增
          </el-button>
          <el-popconfirm title="确定删除选中数据吗？" @confirm="handleDelete">
            <template v-slot:reference>
              <el-button
                v-charge
                :disabled="!multipleSelection.length"
                icon="el-icon-delete"
                style="margin-left: 10px"
                type="danger"
              >
                删除
              </el-button>
            </template>
          </el-popconfirm>
          <el-upload
            ref="upload"
            :action="actionUrl"
            :before-upload="beforeUpload"
            :headers="headers"
            :multiple="false"
            :on-error="handleError"
            :on-success="handleSuccess"
            :show-file-list="false"
            class="avatar-uploader"
          >
            <el-button
              v-charge
              :loading="uploadLoading"
              icon="el-icon-download"
              style="margin-right: 10px;"
              type="primary"
              >导入
            </el-button>
          </el-upload>
          <el-button icon="el-icon-upload2" type="warning" @click="exportFile"
            >导出
          </el-button>
          <el-button
            v-charge
            icon="el-icon-document"
            type="info"
            @click="templateDownload"
          >
            模版下載
          </el-button>
        </div>
        <el-table
          ref="multipleSelection"
          v-loading="loading"
          :cell-style="{'text-align': 'center'}"
          :data="tableData"
          :default-sort="getSorterDirection(queryParam, true)"
          :header-cell-style="{'text-align': 'center'}"
          :max-height="tableMaxHeight"
          :style="{width: '100%'}"
          size="mini"
          @row-dblclick="row => isCharge === 1 && showDialog('addEdit', row)"
          @selection-change="handleSelectionChange"
          @sort-change="sortChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column
            :index="
              index =>
                index +
                1 +
                (queryParam.pageBean.page - 1) * queryParam.pageBean.pageSize
            "
            fixed
            label="序号"
            type="index"
            width="55"
          />
          <el-table-column
            :formatter="({inspect}) => inspect || '-'"
            label="侦察情报"
            min-width="120"
            prop="inspect"
            show-overflow-tooltip
          />
          <el-table-column
            :formatter="({operationpPlan}) => operationpPlan || '-'"
            label="作战计划"
            min-width="120"
            prop="operationpPlan"
            show-overflow-tooltip
          />
          <el-table-column
            :formatter="({operationControl}) => operationControl || '-'"
            label="作战控制"
            min-width="120"
            prop="operationControl"
            show-overflow-tooltip
          />
          <el-table-column
            :formatter="({politicalWork}) => politicalWork || '-'"
            label="政治工作"
            min-width="120"
            prop="politicalWork"
            show-overflow-tooltip
          />
          <el-table-column
            :formatter="({afterloadingSupport}) => afterloadingSupport || '-'"
            label="后装保障"
            min-width="120"
            prop="afterloadingSupport"
            show-overflow-tooltip
          />
          <el-table-column
            :formatter="({createTime}) => createTime || '-'"
            label="创建时间"
            min-width="120"
            prop="createTime"
            sortable="custom"
            show-overflow-tooltip
          />
        </el-table>
        <el-pagination
          ref="paginationPanel"
          :current-page="queryParam.pageBean.page"
          :page-size="queryParam.pageBean.pageSize"
          :page-sizes="[20, 30, 40, 50]"
          :total="queryParam.pageBean.total"
          align="right"
          background
          class="bbsl-pagination"
          layout="prev, pager, next,total, sizes, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </div>

    <!--  新增修改弹层  -->
    <AddEditDialog
      v-model="dialogs.addEditDialog"
      :row-info="rowInfo"
      :activeTreeItem="activeTreeItem"
      @submit="addEditSubmit"
    />
  </div>
</template>

<script>
import {TableMixin} from '@/mixins/tableMixin'
import {getSorterDirection, refineRequestBody} from '@/utils/requestWrappers'
import AddEditDialog from './components/AddEditDialog.vue'

import {mapState} from 'vuex'
import * as api from '@/api/examDataMenu/examActivityData/controlDataMenu'
import {dictionaryEscape} from '@/utils/dictionary'
import {treeDataByDem} from '@/api/systemInterface'
import treeSide from '@/components/treeSide/index.vue'
import {setQueryValue} from '@/utils/requestWrappers'

export default {
  name: 'ControlDataMenu',
  components: {
    AddEditDialog,
    treeSide
  },
  mixins: [TableMixin],
  data() {
    return {
      tableData: [], // 表格数据
      // 查询对象
      queryParam: {
        pageBean: {pageSize: 20, page: 1, total: 0},
        querys: [
          {operation: 'LIKE', property: 'inspect'},
          {operation: 'LIKE', property: 'org_id_'}
        ],
        sorter: [{direction: 'DESC', property: 'createTime'}]
      },
      // 统一管理多个弹层
      dialogs: {
        addEditDialog: false // 新增修改弹层
      },
      rowInfo: {}, // 保存行信息
      uploadLoading: false,
      treeData: [],
      activeTreeItem: {}
    }
  },
  computed: {
    actionUrl: _ => window.context.portal + '/biz/data/control/importExcel',
    ...mapState({
      headers: state => ({
        Authorization: `Bearer ${state.login.currentUser.token}`
      })
    })
  },
  created() {
    // 获取树形目录
    this.getTreeData(treeData => {
      // 回调中默认选中第一项并将其id作为参数请求表格
      this.activeTreeItem = treeData[0] || {}
      this.$nextTick(_ => {
        this.$refs.treeSide?.setCurrentKey(treeData[0]?.id)
        this.$refs.treeSide?.expandHandle(true, 2)
        setQueryValue(this.queryParam, 'org_id_', treeData[0]?.id || '')
        this.loadData()
      })
    })
  },
  methods: {
    dictionaryEscape,
    //左边树节点
    currentChange(nodeItem) {
      console.log(nodeItem)

      // 修改对应的字段值
      setQueryValue(this.queryParam, 'org_id_', nodeItem?.id || '')
      this.activeTreeItem = nodeItem || {}
      this.calcTableHeight(500)
      this.queryParam.pageBean.page = 1
      this.loadData()
    },
    //获取树
    async getTreeData(callback) {
      this.treeData = await treeDataByDem()

      // 保证重新刷新树数据后，选中效果不失效
      if (this.activeTreeItem.id) {
        this.$nextTick(_ => {
          this.$refs.treeSide?.setCurrentKey(this.activeTreeItem.id)
        })
      }
      callback && callback(this.treeData)
    },
    // 获取表格数据
    async loadData() {
      try {
        this.loading = true
        const {total = 0, rows = []} = await api.tableData(
          refineRequestBody(this.queryParam)
        )
        this.queryParam.pageBean.total = total
        this.tableData = rows
      } finally {
        this.loading = false
      }
    },

    // 重置搜索
    resetSearch() {
      this.queryParam = this.$options.data().queryParam
      this.loadData()
    },

    // 删除
    async handleDelete(row) {
      let ids = row ? row.id : this.multipleSelection.join()
      const {state} = await api.tableDelete(ids)
      if (state) {
        this.$message.success(`指挥控制数据删除成功`)
        const {page, pageSize, total} = this.queryParam.pageBean
        const totalPages = Math.ceil(total / pageSize) // 计算总页数
        if (totalPages > 1 && page === totalPages) {
          if (this.tableData.length === 1) {
            // 当前页只有一条数据
            this.queryParam.pageBean.page -= 1 // 返回前一页
          }
        }
        await this.loadData()
      }
    },

    //  导入文件上传前
    beforeUpload(file) {
      return new Promise((resolve, reject) => {
        this.uploadLoading = true
        const {size, name} = file
        let passedOrNot = true // 是否通过验证
        const maxSize = 500 * 1024 * 1024 // 20MB
        const typeRegular = /\.(xls|xlsx)$/i
        const verification = [
          {
            condition: !typeRegular.test(name),
            result: () => this.$message.error('只能上传xls或xlsx文件类型')
          }
        ]
        verification.forEach(item => {
          if (item.condition) {
            item.result()
            passedOrNot = false
            this.uploadLoading = false
          }
        })

        passedOrNot ? resolve() : reject()
      })
    },

    // 导入文件上传成功
    async handleSuccess() {
      this.$message.success('指挥控制数据导入成功')
      this.uploadLoading = false
      await this.loadData()
    },

    // 导入文件上传失败
    handleError() {
      this.$message.error('指挥控制数据导入失败，请重试')
      this.uploadLoading = false
    },

    // 导出数据
    async exportFile() {
      await api.exportData(
        refineRequestBody({
          querys: this.queryParam.querys,
          pageBean: {
            pageSize: -1
          }
        })
      )
    },

    // 模板下载
    async templateDownload() {
      window.open(this.portal + '/biz/data/control/downModel', '_blank')
    },

    // 新增修改弹层提交成功后
    addEditSubmit(type) {
      switch (type) {
        case 'add':
          this.queryParam.pageBean.page = 1
          break
        case 'edit':
          break
      }
      this.loadData()
    },

    getSorterDirection
  }
}
</script>
<style lang="scss" scoped>
.bbsl-common-page {
  display: flex;
  flex-direction: column;
  row-gap: 10px;

  .page-content {
    display: flex;
    height: calc(100% - 70px);
    column-gap: 10px;

    .tree-container {
      height: 100%;
      min-width: 300px;
      background: #fff;
      border-radius: 20px;
      padding: 20px 20px;
      box-shadow: 0px 0px 12px 0 rgba($color: #000000, $alpha: 0.1);
      box-sizing: border-box;
    }

    .bbsl-table-content {
      height: 100%;
      flex: 1;
      margin-top: 0;
      box-sizing: border-box;
    }
  }
}
.type-tag {
  margin: 0 2px;
}

.common-tree-container {
  height: calc(100% - 70px);
  margin-top: 0.52083vw;
  padding: 1.04167vw 1.04167vw;
  background-color: #fff;
  position: relative;
  overflow-y: auto;
  box-sizing: border-box;
  border-radius: 20px;
  box-shadow: 0px 0px 0.625vw 0 rgba(92, 102, 83, 0.2);
}

a {
  text-decoration: none;
  color: #ffffff;
}

.title {
  width: 100%;
  margin-bottom: 10px;

  i {
    color: #1289fe;
    font-size: 25px;
  }

  span {
    font-size: 25px;
  }
}

::v-deep .el-tree {
  border: none;
}

.avatar-uploader {
  display: inline-block;
  margin-left: 10px;
}

::v-deep .el-tree-node__content {
  padding: 5px 0;
}
</style>
