<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="110px">
      <el-form-item label="院校招生代码" prop="collegeCode">
        <el-input v-model="queryParams.collegeCode" 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 label="年份" prop="year">
        <el-input v-model="queryParams.year" placeholder="请输入年份" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="所在地" prop="location">
        <el-input v-model="queryParams.location" placeholder="请输入所在地" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="批次" prop="batch">
        <el-input v-model="queryParams.batch" placeholder="请输入批次" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="录取最低分" prop="score">
        <el-input v-model="queryParams.score" placeholder="请输入录取最低分" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="录取最低分位次" prop="seat">
        <el-input v-model="queryParams.seat" placeholder="请输入录取最低分位次" clearable
                  @keyup.enter.native="handleQuery"/>
      </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="specialProject">
        <el-input v-model="queryParams.specialProject" 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 label="专业别名通用" prop="marjorNameText">
        <el-input v-model="queryParams.marjorNameText" placeholder="请输入专业别名" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="专业备注" prop="marjorDirection">
        <el-input v-model="queryParams.marjorDirection" placeholder="请输入专业备注" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="udid" prop="udid">
        <el-input v-model="queryParams.udid" placeholder="请输入udid" 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="['back:busiWishUniversitySubmitMarjors:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['back:busiWishUniversitySubmitMarjors:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                   v-hasPermi="['back:busiWishUniversitySubmitMarjors:remove']">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   v-hasPermi="['back:busiWishUniversitySubmitMarjors:export']">导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-position" size="mini" @click="handleExpandAll">
          {{ expandAll ? '全部收起' : '全部展开' }}
        </el-button>
      </el-col>
      <el-col v-if="!isInDialog" :span="1.5">
        <el-button type="info" plain icon="el-icon-setting" size="mini" @click="bindingSetting=true">
          绑定搜索设置
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <dynamic-table ref="table" v-loading="loading" :rows="busiWishUniversitySubmitMarjorsList" :columns="enrollColumns"
                   row-key="id" @selection-change="handleSelectionChange">
      <template #expand="{row}">
        <div style="padding: 0 50px">
          <dynamic-table :rows="row.bindPlan" :columns="planColumns" :show-header="false" size="small"
                         border row-class-name="nested-table-row" style="background-color: #eeeeee"></dynamic-table>
        </div>
      </template>
      <template #action="scope">
        <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                   v-hasPermi="['back:busiWishUniversitySubmitMarjors:edit']">修改
        </el-button>
        <el-button size="mini" type="text" icon="el-icon-position" @click="handleToggleExpand(scope.row)">展开绑定
        </el-button>
        <el-button v-if="!isInDialog" size="mini" type="text" icon="el-icon-connection"
                   @click="handleBindOpen(scope.row)">修改绑定
        </el-button>
        <!--<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['back:busiWishUniversitySubmitMarjors:remove']">删除</el-button>-->
      </template>
    </dynamic-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                :page-sizes="[10, 20, 30, 40, 50, 100, 200]"
                @pagination="getList"/>

    <!-- 添加或修改院校专业分数线对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学校编码" prop="universityCode">
          <el-input v-model="form.universityCode" placeholder="请输入学校编码"/>
        </el-form-item>
        <el-form-item label="学校名称" prop="universityName">
          <el-input v-model="form.universityName" placeholder="请输入学校名称"/>
        </el-form-item>
        <el-form-item label="院校代码" prop="collegeCode">
          <el-input v-model="form.collegeCode" placeholder="请输入院校代码"/>
        </el-form-item>
        <el-form-item label="年份" prop="year">
          <el-input v-model="form.year" placeholder="请输入年份"/>
        </el-form-item>
        <el-form-item label="所在地" prop="location">
          <el-input v-model="form.location" placeholder="请输入所在地"/>
        </el-form-item>
        <el-form-item label="录取最低分" prop="score">
          <el-input v-model="form.score" placeholder="请输入录取最低分"/>
        </el-form-item>
        <el-form-item label="录取最低分位次" prop="seat">
          <el-input v-model="form.seat" placeholder="请输入录取最低分位次"/>
        </el-form-item>
        <el-form-item label="招生人数" prop="num">
          <el-input v-model="form.num" placeholder="请输入招生人数"/>
        </el-form-item>
        <el-form-item label="录取人数" prop="numReal">
          <el-input v-model="form.numReal" placeholder="请输入录取人数"/>
        </el-form-item>
        <el-form-item label="录取最高分" prop="scoreRealTop">
          <el-input v-model="form.scoreRealTop" placeholder="请输入录取最高分"/>
        </el-form-item>
        <el-form-item label="录取最高分位次" prop="seatRealTop">
          <el-input v-model="form.seatRealTop" placeholder="请输入录取最高分位次"/>
        </el-form-item>
        <el-form-item label="录取平均分" prop="scoreRealAverage">
          <el-input v-model="form.scoreRealAverage" placeholder="请输入录取平均分"/>
        </el-form-item>
        <el-form-item label="录取平均分位次" prop="seatRealAverage">
          <el-input v-model="form.seatRealAverage" placeholder="请输入录取平均分位次"/>
        </el-form-item>
        <el-form-item label="批次" prop="batch">
          <el-input v-model="form.batch" placeholder="请输入批次"/>
        </el-form-item>
        <el-form-item label="层次" prop="level">
          <el-input v-model="form.level" placeholder="请输入层次"/>
        </el-form-item>
        <el-form-item label="科类" prop="liberalScience">
          <el-input v-model="form.liberalScience" placeholder="请输入科类"/>
        </el-form-item>
        <el-form-item label="学校ID" prop="universityId">
          <el-input v-model="form.universityId" placeholder="请输入院校"/>
        </el-form-item>

        <el-form-item label="专业名" prop="marjorName">
          <el-input v-model="form.marjorName" placeholder="请输入专业名"/>
        </el-form-item>
        <el-form-item label="包含专业" prop="marjorBelongs">
          <el-input v-model="form.marjorBelongs" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="专业方向" prop="marjorDirection">
          <el-input v-model="form.marjorDirection" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="专项" prop="specialProject">
          <el-input v-model="form.specialProject" placeholder="请输入专项"/>
        </el-form-item>
        <el-form-item label="首选科目说明" prop="courseRemark0">
          <el-input v-model="form.courseRemark0" placeholder="请输入首选科目说明"/>
        </el-form-item>
        <el-form-item label="再选科目说明" prop="courseRemark1">
          <el-input v-model="form.courseRemark1" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="选考要求" prop="course">
          <el-input v-model="form.course" placeholder="请输入选考要求"/>
        </el-form-item>
        <el-form-item label="再选科目或" prop="course1">
          <el-input v-model="form.course1" placeholder="请输入再选科目或"/>
        </el-form-item>
        <el-form-item label="再选科目与" prop="course2">
          <el-input v-model="form.course2" placeholder="请输入再选科目与"/>
        </el-form-item>

        <el-form-item label="专业名" prop="marjorName">
          <el-input v-model="form.marjorName" placeholder="请输入专业名称"/>
        </el-form-item>
        <el-form-item label="专业别名通用" prop="marjorNameText">
          <el-input v-model="form.marjorNameText" placeholder="请输入专业别名"/>
        </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 v-if="bindingDialog" :visible.sync="bindingDialog" :title="bindingTitle" width="90%">
      <busi-wish-university-submit-recruit-plan ref="enrollPage" :binding-enroll="bindingEnroll" :binding-copy-fields="bindingFields"/>
      <div slot="footer" class="dialog-footer">
        <el-checkbox v-model="bindingConfirm" style="margin-right: 20px">绑定确认</el-checkbox>
        <el-button type="primary" @click="handleBind">确 定</el-button>
        <el-button @click="handleBindClose">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="bindingSetting" title="绑定搜索字段设置">
      <el-checkbox-group v-model="bindingFields">
        <el-checkbox v-for="col in planColumns" :key="col.label" :label="col.prop">{{ col.label }}</el-checkbox>
      </el-checkbox-group>
    </el-dialog>
  </div>
</template>

<script>
import {
  listBusiWishUniversitySubmitMarjors,
  getBusiWishUniversitySubmitMarjors,
  delBusiWishUniversitySubmitMarjors,
  addBusiWishUniversitySubmitMarjors,
  updateBusiWishUniversitySubmitMarjors,
  bindEnrollPlanMajor
} from "@/api/back/busiWishUniversitySubmitMarjors";
import RecruitPlanEnrollMajorBinding from "@/views/back/components/RecruitPlanEnrollMajorBinding";
import DynamicTable from "@/components/dynamic-table/index.vue";
import BusiWishUniversitySubmitRecruitPlan from "@/views/back/busiWishUniversitySubmitRecruitPlan/index-bak.vue";

export default {
  name: "BusiWishUniversitySubmitMarjors",
  components: {BusiWishUniversitySubmitRecruitPlan, DynamicTable},
  props: {
    bindingPlan: {
      type: Object,
      default: () => ({id: 0, bindEnrollList: []})
    },
    bindingCopyFields: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 院校专业分数线表格数据
      busiWishUniversitySubmitMarjorsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        collegeCode: null,
        year: null,
        location: null,
        batch: null,
        level: null,
        liberalScience: null,
        type: null,
        marjorId: null,
        universityId: null,
        universityCode: null,
        universityName: null,
        marjorName: null,
        marjorNameText: null,
        marjorBelongs: null,
        marjorDirection: null,
        specialProject: null,
        courseRemark0: null,
        courseRemark1: null,
        course: null,
        course0: null,
        course1: null,
        course2: null,
        score: null,
        seat: null,
        num: null,
        numReal: null,
        scoreRealTop: null,
        seatRealTop: null,
        scoreRealAverage: null,
        seatRealAverage: null,
        createTime: null,
        status: null,
        udid: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        year: [
          {required: true, message: "年份不能为空", trigger: "blur"}
        ],
        num: [
          {required: true, message: "招生人数不能为空", trigger: "blur"}
        ],
        status: [
          {required: true, message: "状态(0:无效,1:有效)不能为空", trigger: "blur"}
        ],
        udid: [
          {required: true, message: "udid不能为空", trigger: "blur"}
        ]
      },
      // add for binding
      expandAll: true,
      bindingSetting: false,
      // + add for bind plan
      bindingTitle: '',
      bindingDialog: false,
      bindingEnroll: null,
      bindingEnrollRaw: null,
      bindingConfirm: true,
      bindingFields: ['location', 'universityCode', 'marjorName'],
    };
  },
  computed: {
    isInDialog() {
      return this.bindingPlan.id
    },
    enrollColumns() {
      const baseColumns = [
        {
          type: 'selection',
          prop: 'selection',
          width: 50
        },
        ...RecruitPlanEnrollMajorBinding.sharedColumns.filter(c => c.disableForEnroll !== true),
        {
          prop: 'action',
          label: '操作',
          slotBody: 'action',
          width: 100
        }];
      if (!this.isInDialog) {
        baseColumns.push({
          type: 'expand',
          prop: 'expand',
          width: 40,
          slotBody: 'expand'
        })
      }
      return baseColumns
    },
    planColumns() {
      return RecruitPlanEnrollMajorBinding.sharedColumns
    }
  },
  mounted() {
    // assign default query parameters if binding plan is not empty
    if (this.isInDialog) {
      const copyParams = this.bindingCopyFields || []
      copyParams.forEach(key => {
        this.queryParams[key] = this.bindingPlan[key]
      })
    }
    this.getList();
  },
  methods: {
    // 展开操作
    handleExpandAll() {
      this.expandAll = !this.expandAll
      this._applyRowsExpand()
    },
    _applyRowsExpand() {
      this.busiWishUniversitySubmitMarjorsList.forEach(row => {
        this.$refs.table.tableCore.toggleRowExpansion(row, this.expandAll)
      })
    },
    handleToggleExpand(row) {
      this.$refs.table.tableCore.toggleRowExpansion(row)
    },
    /** 查询院校专业分数线列表 */
    getList() {
      this.loading = true;
      listBusiWishUniversitySubmitMarjors(this.queryParams).then(response => {
        this.recalculateListWithBindList(response.rows)
        response.rows.forEach(row => row.bindPlan = row.bindPlan ? [row.bindPlan] : []) // safe init
        this.busiWishUniversitySubmitMarjorsList = response.rows;
        this.total = response.total;
        this.loading = false;
        if (this.expandAll) setTimeout(() => this._applyRowsExpand(), 200) // short wait for table to render
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        collegeCode: null,
        year: null,
        location: null,
        batch: null,
        level: null,
        liberalScience: null,
        type: null,
        marjorId: null,
        universityId: null,
        universityCode: null,
        universityName: null,
        marjorName: null,
        marjorNameText: null,
        marjorBelongs: null,
        marjorDirection: null,
        specialProject: null,
        courseRemark0: null,
        courseRemark1: null,
        course: null,
        course0: null,
        course1: null,
        course2: null,
        score: null,
        seat: null,
        num: null,
        numReal: null,
        scoreRealTop: null,
        seatRealTop: null,
        scoreRealAverage: null,
        seatRealAverage: null,
        createTime: null,
        status: 0,
        udid: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      this.resetPlanEnrollList(selection)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加院校专业分数线";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getBusiWishUniversitySubmitMarjors(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改院校专业分数线";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateBusiWishUniversitySubmitMarjors(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBusiWishUniversitySubmitMarjors(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除院校专业分数线编号为"' + ids + '"的数据项？').then(function () {
        return delBusiWishUniversitySubmitMarjors(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('back/busiWishUniversitySubmitMarjors/export', {
        ...this.queryParams
      }, `busiWishUniversitySubmitMarjors_${new Date().getTime()}.xlsx`)
    },
    // + add for bind enroll
    handleBindOpen(row) {
      // deep clone row
      this.bindingEnroll = JSON.parse(JSON.stringify(row))
      this.bindingEnrollRaw = row
      this.bindingDialog = true
      this.bindingTitle = `绑定--${row.year},${row.location},${row.universityName},${row.level},${row.type},${row.marjorName},${row.marjorDirection || ''}`
    },
    handleBindClose() {
      this.bindingDialog = false
    },
    async handleBind() {
      if (this.bindingEnroll.bindPlan.length !== 1) {
        this.$modal.msgWarning('请选择1个计划')
        return
      }
      const oldBind = this.bindingEnrollRaw.bindPlan.map(item => item.id)
      const newBind = this.bindingEnroll.bindPlan.map(item => item.id)
      oldBind.sort((a, b) => a - b)
      newBind.sort((a, b) => a - b)
      if (oldBind == newBind) {
        this.$modal.msgWarning('未做任何修改')
        return
      }
      if (this.bindingConfirm) {
        const confirmMsg = `确认将${this.bindingEnroll.marjorName}(${this.bindingEnroll.id}) 与 [${newBind.toString()}] 绑定？`
        await this.$modal.confirm(confirmMsg)
      }
      const data = {
        enrollId: this.bindingEnroll.id,
        planId: newBind[0]
      }
      const res = await bindEnrollPlanMajor(data)
      this.$message.success(res.msg || '绑定成功')
      this.bindingDialog = false
      this.getList()
    },
    /* enroll list with selected */
    resetPlanEnrollList(selection) {
      if (this.isInDialog) {
        this.bindingPlan.bindEnrollList = selection || []
      }
    },
    recalculateListWithBindList(rows) {
      if (this.isInDialog) {
        // keep the new order of bind list
        const bindList = this.bindingPlan.bindEnrollList.map(oldRow => {
          const newRow = rows.find(row => row.id == oldRow.id)
          return newRow || oldRow
        })
        const restList = rows.filter(item => !bindList.includes(item))
        // 重置列表
        rows.length = 0
        rows.push(...bindList, ...restList)
        this.bindingPlan.bindEnrollList = bindList

        // 重置选中
        setTimeout(() => {
          // NOTE: Here we use bindList, the closure variable will keep the old value
          // Or else the selection will be reset to empty when table re-render
          bindList.forEach(row => {
            this.$refs.table.tableCore.toggleRowSelection(row, true)
          })
        }, 200)
      }
    }
  }
};
</script>

<style lang="scss">
.nested-table-row {
  background-color: #eeeeee;
}
</style>
