<template>
  <div class="table-container">
    <vab-query-form>
      <div class="title">
        <div class="left">
          <el-form label-width="100px" :inline="true">
            <el-form-item label="线路名称：" prop="id">
              <el-input v-model="search.name" placeholder="请输入" clearable />
            </el-form-item>
            <el-form-item label="期次：" prop="id">
              <el-cascader 
                v-model="search.projectId" 
                :options="options" 
                :props="{ checkStrictly: true, label: 'name', value: 'id' , children:'children',}" 
                clearable />
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" native-type="submit" @click="handleQuery">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="right">
          <el-button icon="el-icon-plus" type="primary" @click="handleAdd">
            添加
          </el-button>
          <el-button icon="el-icon-delete" type="danger" @click="handleDelete">
            删除
          </el-button>
          <UploadExcel style="margin-left: 10px;" @getResult="getMyExcelData"></UploadExcel>
          <ExportExcel :exportList="exportExcel" :useType="'export'" partsName="线路"></ExportExcel>
          <ExportExcel :exportList="templateExcel" :useType="'template'" partsName="线路模板"></ExportExcel>
        </div>
      </div>

      <el-table ref="tableSort" v-loading="listLoading" :data="list" :element-loading-text="elementLoadingText"
        header-cell-class-name="table_header_style" border
        :height="height" @selection-change="setSelectRows">
        <el-table-column show-overflow-tooltip type="selection" width="55" align="center"></el-table-column>
        <el-table-column show-overflow-tooltip label="编号" prop="id" align="center" sortable></el-table-column>
        <el-table-column show-overflow-tooltip label="编码" prop="nemCode" align="center" sortable></el-table-column>
        <el-table-column show-overflow-tooltip label="线路名称" prop="name" align="center" sortable></el-table-column>
        <el-table-column show-overflow-tooltip label="别称" prop="aname" align="center" sortable></el-table-column>
        <!-- :formatter="nameEcho"  -->
        <el-table-column :formatter="projectIdFormatter" show-overflow-tooltip label="期次" prop="projectId" align="center" sortable></el-table-column>
        <el-table-column show-overflow-tooltip label="装机容量" prop="capacity" align="center" sortable></el-table-column>
        <el-table-column show-overflow-tooltip label="装机单位" prop="capacityUnit" align="center" sortable></el-table-column>
        <el-table-column show-overflow-tooltip label="装机数量" prop="quantity" align="center" sortable></el-table-column>
        <el-table-column show-overflow-tooltip label="顺序" prop="orderNum" align="center" sortable></el-table-column>
        <el-table-column show-overflow-tooltip label="操作" width="100px" fixed="right">
          <template #default="{ row }" fixed="right">
            <el-button type="text" @click="handleEdit(row)">编辑</el-button>
            <el-button type="text" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination :background="background" :current-page="queryForm.pageNo" :layout="layout"
        :page-size="queryForm.pageSize" :total="total" @current-change="handleCurrentChange"
        @size-change="handleSizeChange"></el-pagination>
      <table-edit ref="edit" :options="options" @save-success="fetchData"></table-edit>
    </vab-query-form>
  </div>
</template>
<script>
import UploadExcel from '@/components/UploadExcel/index'
import ExportExcel from '@/components/ExportExcel/index'
import api from '@/api/station'
import apis from '@/api/table'
import TableEdit from './components/TableEdit'
import { recursionTree } from '@/utils/deepTree'
export default {
  components: {
    UploadExcel,
    ExportExcel,
    TableEdit,
  },
  computed: {
    height() {
      return this.$baseTableHeight() + 50
    },
  },
  data() {
    return {
      projectIdAll:[],
      search: {
        name:"",
        projectId:"",
      },
      deepTreeData: '',
      fuzzyQuery: '',
      listLoading: true,
      list: [],
      options: [],
      exportExcel: [],
      templateExcel: [],
      elementLoadingText: '正在加载...',
      selectRows: '',
      layout: 'total, sizes, prev, pager, next, jumper',
      total: 0,
      background: true,
      exportList: [],
      stationList: [],
      value: '',
      queryForm: {
        pageNo: 1,
        pageSize: 20,
      },
    };
  },
  created() {
    this.fetchData()
    this.getTree()
  },
  methods: {
    projectIdFormatter(row){
      for (const iterator of this.projectIdAll) {
        if(row.projectId === iterator.id) {
          return iterator.name
        }
      }
    },
    handleQuery() {
      this.queryForm.pageNo = 1
      this.fetchData()
    },
    nameEcho(row){
      let arr = row.projectid.split(",")
      let str = ""
      if(this.deepTreeData) {
        this.deepTreeData.forEach(element => {
          if(arr[arr.length -1] == element.id){
            str = element.name
          }
        });
      }
      return str
    },
    getTree() {
      api.sttreeProjecttrees().then(res => {
        if (res.data) {
          this.options = res.data
          res.data.forEach(element => {
            if(element.children) {
              element.children.forEach(item => {
                this.projectIdAll.push(item)
              });
            }
          });
          this.deepTreeData = recursionTree(res.data)
        }
      })
    },
    getMyExcelData(val) {
      val.forEach(item => {
        api.addLine(item).then(res => {
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: '添加成功!'
            });
            this.fetchData()
          }
        })
      })
    },
    fetchData() {
      this.listLoading = true
      api.lines({
        id: '',
        name: this.search.name,
        projectId: this.search.projectId[this.search.projectId.length - 1] || "",
        pageNum: this.queryForm.pageNo,
        pageSize: this.queryForm.pageSize,
      }).then(res => {
        if (res.data) {
          this.list = res.data.records
          this.total = res.data.total
          this.listLoading = false
          this.templateExcel = [
            {
              id: '',
              nemCode: '',
              name: '',
              aname: '',
              projectId: '',
              capacity: '',
              capacityUnit: '',
              quantity: '',
              orderNum: '',
            }
          ]
          // 导出
          let exportExcel = []
          res.data.records.forEach(item => {
            exportExcel.push({
              id: item.id,
              nemCode: item.nemCode,
              name: item.name,
              aname: item.aname,
              projectId: item.projectId,
              capacity: item.capacity,
              capacityUnit: item.capacityUnit,
              quantity: item.quantity,
              orderNum: item.orderNum,
            })
          })
          this.exportExcel = exportExcel
        }
      })
    },
    handleSizeChange(val) {
      this.queryForm.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.queryForm.pageNo = val
      this.fetchData()
    },
    handleAdd() {
      this.$refs['edit'].showEdit()
    },
    handleEdit(row) {
      this.$refs['edit'].showEdit(row)
    },
    handleDelete(row) {
      if (row.id || this.selectRows.length > 0) {
        this.$baseConfirm('你确定要删除吗', null, async () => {
          let ids = ''
          if (this.selectRows.length > 0) {
            ids = this.selectRows.map((item) => item.id).join()
          }
          api.deleteLine({
            id: row.id || ids
          }).then(res => {
            if (res.data) {
              this.$baseMessage('删除成功', 'success')
              this.fetchData()
            }
          })
        })
      } else {
        this.$baseMessage('未选中任何行', 'error')
        return false
      }
    },
    setSelectRows(val) {
      this.selectRows = val
    },
  },
}
</script>
<style lang="less" scoped>
.title {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.left {
  display: flex;
  flex-direction: row;
  align-items: center;

  .left-item {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-right: 10px;
  }
}
</style>