<template>
  <div v-loading="loading" class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="匹配模式" prop="matchType">
        <el-select v-model="queryParams.matchType" filterable @change="handleQuery">
          <el-option v-for="item in matchTypes" :key="item.value" :value="item.value" :label="item.label" />
        </el-select>
      </el-form-item>
      <el-form-item label="计划年份" prop="planYear">
        <el-select v-model="queryParams.planYear" filterable @change="handleQuery">
          <el-option v-for="item in bindingYears.planYears" :key="item" :value="item" :label="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="专业年份" prop="year">
        <el-select v-model="queryParams.year" filterable @change="handleQuery">
          <el-option v-for="item in bindingYears.majorYears" :key="item" :value="item" :label="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="省份" prop="location">
        <el-select v-model="queryParams.location" filterable @change="handleQuery">
          <el-option v-for="item in locationList" :key="item.id" :value="item.sname" :label="item.sname" />
        </el-select>
      </el-form-item>
      <el-form-item label="批次" prop="level">
        <el-input v-model="queryParams.level" placeholder="请输入层次" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="科类" prop="type">
        <el-input v-model="queryParams.type" placeholder="请输入类别" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="院校编码" prop="universityCode">
        <el-input v-model="queryParams.universityCode" placeholder="请输入院校编码" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="院校名" prop="universityName">
        <el-input v-model="queryParams.universityName" placeholder="请输入院校名" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item v-if="false" label="院校招生代码" prop="collegeCode">
        <el-input v-model="queryParams.collegeCode" placeholder="请输入院校招生代码" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item v-if="false" label="专业招生代码" prop="marjorBelongs">
        <el-input v-model="queryParams.marjorBelongs" placeholder="请输入专业招生代码" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="专业名" prop="marjorName">
        <el-input v-model="queryParams.marjorName" placeholder="请输入专业名" 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="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-folder" size="mini" @click="handleExpand">展开/收起</el-button>
      </el-col>
      <right-toolbar ref="toolbar" :showSearch.sync="showSearch" @queryTable="getList" :columns="column.plan">
        <el-divider>
          <el-checkbox v-model="column.showManual">展示手工修正备注</el-checkbox>
        </el-divider>
        <column-transfer :columns="column.manual" />
        <el-divider>专业线列表</el-divider>
        <column-transfer :columns="column.major" />
        <el-button type="primary" class="mt12" @click="keepColumnConfig(),$refs.toolbar.open=false">暂存配置</el-button>
        <el-button type="info" class="mt12" @click="resetColumnConfig">重置</el-button>
      </right-toolbar>
    </el-row>
    <dynamic-table ref="table" :columns="column.plan" :rows="rows" default-expand-all border row-class-name="plan-row">
      <template #expand="{row}">
        <div class="pl50 pr50">
          <template v-if="column.showManual">
            <div class="fx-row ai-cen direction-manual-container mb8">
              <el-divider direction="vertical" />
              <span class="f15 bold">手工修正备注</span>
            </div>
            <dynamic-table :columns="column.manual" :rows="[row.directionManual]" border />
            <div class="fx-row ai-cen direction-manual-container mb8 mt12">
              <el-divider direction="vertical" />
              <span class="f15 bold">专业线列表</span>
            </div>
          </template>
          <dynamic-table :columns="column.major" :rows="row.bindingMajorList" border>
            <template #tag="{row:major}">
              <el-tag v-if="major.isAlgorithmRecommended" type="warning" size="small">算法推荐</el-tag>
              <el-tag v-if="major.isManualBound" type="success" size="small">已绑定</el-tag>
            </template>
          </dynamic-table>
        </div>
      </template>
    </dynamic-table>
    <pagination :total="total" :page-sizes="[20,50,100,200]" :page.sync="pageParams.pageNum" :limit.sync="pageParams.pageSize" @pagination="getList" />
    <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}?location=${queryParams.location}`"
        :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">
          <span>仅允许导入xls、xlsx格式文件。</span>
        </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 {locationList} from "@/api/voluntary/sysLocations";
import {
  exportManualBindingList,
  getManualBindingList,
  getManualBindingYears
} from "@/api/back/busiWishUniversitySubmitRecruitPlan";
import {getToken} from "@/utils/auth";
import DynamicTable from "@/components/dynamic-table/index.vue";
import ColumnTransfer from "@/components/RightToolbar/ColumnTransfer.vue";

const keyStorageRecruitPlanQuery = "keyStorageRecruitPlanQuery";
const keyStorageRecruitPlanColumns = "keyStorageRecruitPlanColumns";

export default {
  name: "index",
  components: {ColumnTransfer, DynamicTable},
  data() {
    return {
      loading: false,
      allExpand: true,
      // constants options
      matchTypes : [{label: '一对一', value: 'O'}, {label: '一对多', value: 'M'}],
      bindingYears: { planYears: [], majorYears: []},
      locationList: [],
      // search features
      queryParams: {
        matchType: 'M', // O: One, M: Many
        planYear: '2022', // 计划年度
        year: '2021', // 专业年度
        location: '湖南',
        universityCode: null,
        universityName: null,
        batch: null,
        level: null,
        type: null,
        collegeCode: null,
        marjorBelongs: null,
        marjorName: null
      },
      pageParams: {
        pageNum: 1,
        pageSize: 20
      },
      showSearch: true,
      column: {
        plan:[
          {key: 1, prop: 'expand', type: 'expand', label: '展开', slotBody: 'expand', hidden: false},
          {key: 2, prop: 'year', label: '年度', hidden: false},
          {key: 3, prop: 'universityName', label: '院校', hidden: false},
          {key: 4, prop: 'collegeCode', label: '招生代码', hidden: false},
          {key: 5, prop: 'group', label: '专业组', hidden: false},
          {key: 6, prop: 'type', label: '科类', hidden: false},
          {key: 7, prop: 'level', label: '批次', hidden: false},
          {key: 8, prop: 'marjorName', label: '专业名', hidden: false},
          {key: 9, prop: 'marjorDirection', label: '专业备注', hidden: false},
          {key: 10, prop: 'specialProject', label: '专项', hidden: false},
          {key: 11, prop: 'xuezhi', label: '学制', hidden: false},
        ],
        manual: [
          {key: 1, prop: 'count', label: '计划数', hidden: false},
          {key: 2, prop: 'xuezi', label: '学制', hidden: false},
          {key: 3, prop: 'schoolLocation', label: '校址', hidden: false},
          {key: 4, prop: 'invalidRemark', label: '无效备注', hidden: false},
          {key: 5, prop: 'specialType', label: '特殊类型', hidden: false},
          {key: 6, prop: 'direction', label: '方向', hidden: false},
          {key: 7, prop: 'hasDirection', label: '方向(包含)', hidden: false}
        ],
        showManual: true,
        major: [
          {key: 1, prop: 'tag', label: '标签', slotBody: 'tag', hidden: false},
          {key: 2, prop: 'year', label: '年度', hidden: false},
          {key: 3, prop: 'universityName', label: '院校', hidden: false},
          {key: 4, prop: 'group', label: '组名', hidden: false},
          {key: 5, prop: 'type', label: '科类', hidden: false},
          {key: 6, prop: 'level', label: '批次', hidden: false},
          {key: 7, prop: 'specialProject', label: '特殊类型', hidden: false},
          {key: 8, prop: 'marjorName', label: '专业名', hidden: false},
          {key: 9, prop: 'marjorDirection', label: '专业方向', hidden: false}
        ]
      },
      rows: [],
      total: 0,
      // upload options
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/back/busiWishUniversitySubmitRecruitPlan/importManualBindingList"
      }
    }
  },
  mounted() {
    this.readConfiguration()
    this.initPageOptions()
  },
  beforeDestroy() {
    this.keepColumnConfig()
    this.keepQueryConfig()
  },
  methods: {
    handleExpand() {
      const table = this.$refs.table.tableCore
      this.rows.forEach(row => table.toggleRowExpansion(row, !this.allExpand))
      this.allExpand = !this.allExpand
    },
    keepColumnConfig() {
      localStorage.setItem(keyStorageRecruitPlanColumns, JSON.stringify(this.column))
    },
    resetColumnConfig() {
      const pureData = this.$options.data()
      this.column = pureData.column
    },
    keepQueryConfig() {
      localStorage.setItem(keyStorageRecruitPlanQuery, JSON.stringify(this.queryParams))
    },
    readConfiguration() {
      const query = localStorage.getItem(keyStorageRecruitPlanQuery)
      if (query) {
        try {
          this.queryParams = JSON.parse(query)
        } catch (e) {
          console.log('Error for reading query cache from local storage', e)
        }
      }
      const columnConfig = localStorage.getItem(keyStorageRecruitPlanColumns)
      if (columnConfig) {
        try{
          this.column = JSON.parse(columnConfig)
        }catch (e) {
          console.log('Error for reading column cache from local storage', e)
        }
      }
    },
    async initPageOptions() {
      this.loading = true
      const {planYears, majorYears} = await getManualBindingYears()
      this.bindingYears.planYears = planYears
      this.bindingYears.majorYears = majorYears

      const locationRes = await locationList({level: 1})
      this.locationList = locationRes.data
      this.loading = false

      this.handleQuery()
    },
    handleQuery() {
      this.pageParams.pageNum = 1
      this.getList()
      this.keepQueryConfig()
    },
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    getList() {
      this.loading = true
      getManualBindingList(this.queryParams, this.pageParams).then(res => {
        this.total = res.total
        this.rows = res.rows
      }).finally(() => this.loading = false)
    },
    handleExport() {
      this.download('back/busiWishUniversitySubmitRecruitPlan/exportManualBindingList', {
        ...this.queryParams
      }, `manual_binding_${new Date().getTime()}.xlsx`)
    },
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      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();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
}
</script>

<style scoped>
.direction-manual-container .el-divider--vertical {
  width: 3px;
  background-color: var(--current-color);
}
</style>
<style>
.el-table tr.plan-row {
  background-color: #ecf5ff !important;
}
.el-table tr.plan-row:hover>td,
.el-table tr.plan-row.current-row>td {
  background-color: var(--current-color) !important;
  color: #FFFFFF !important;
}
</style>
