<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <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="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="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="course">
        <el-input v-model="queryParams.course" 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="marjorCode">
        <el-input v-model="queryParams.marjorCode" 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="专项" prop="specialProject">
        <el-input v-model="queryParams.specialProject" 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:busiWishUniversitySubmitRecruitPlan: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:busiWishUniversitySubmitRecruitPlan: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:busiWishUniversitySubmitRecruitPlan: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:busiWishUniversitySubmitRecruitPlan:export']">导出
        </el-button>
      </el-col>
      <template v-if="!isInDialog">
        <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 :span="1.5">
          <el-button type="info" plain icon="el-icon-setting" size="mini" @click="bindingSetting=true">
            绑定搜索设置
          </el-button>
        </el-col>
      </template>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <dynamic-table ref="table" v-loading="loading" :rows="busiWishUniversitySubmitRecruitPlanList"
                   :columns="planColumns" row-key="id" @selection-change="handleSelectionChange">
      <template #expand="{row}">
        <div style="padding: 0 50px">
          <dynamic-table :rows="row.bindEnrollList" :columns="enrollColumns" :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:busiWishUniversitySubmitRecruitPlan:edit']">修改
        </el-button>
        <template v-if="!isInDialog">
          <el-button size="mini" type="text" icon="el-icon-position" @click="handleToggleExpand(scope.row)">展开绑定
          </el-button>
          <el-button 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:busiWishUniversitySubmitRecruitPlan:remove']">删除
          </el-button>
        </template>
      </template>
    </dynamic-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @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="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="批次，对应表中level" prop="batch">
          <el-input v-model="form.batch" placeholder="请输入批次，对应表中level"/>
        </el-form-item>
        <el-form-item label="层次" prop="level">
          <el-input v-model="form.level" placeholder="请输入层次"/>
        </el-form-item>
        <el-form-item label="选科组合" prop="course">
          <el-input v-model="form.course" placeholder="请输入选科组合"/>
        </el-form-item>
        <el-form-item label="科类： 1理科(物理)，0文科(历史), 2文理不分" prop="liberalScience">
          <el-input v-model="form.liberalScience" placeholder="请输入科类： 1理科(物理)，0文科(历史), 2文理不分"/>
        </el-form-item>
        <el-form-item label="代码" prop="marjorId">
          <el-input v-model="form.marjorId" placeholder="请输入代码"/>
        </el-form-item>
        <el-form-item label="院校ID" prop="universityId">
          <el-input v-model="form.universityId" placeholder="请输入院校ID"/>
        </el-form-item>
        <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="marjorCode">
          <el-input v-model="form.marjorCode" 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-item label="包含专业" prop="marjorBelongs">
          <el-input v-model="form.marjorBelongs" 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="planCount">
          <el-input v-model="form.planCount" placeholder="请输入计划数"/>
        </el-form-item>
        <el-form-item label="学费" prop="xuefei">
          <el-input v-model="form.xuefei" placeholder="请输入学费"/>
        </el-form-item>
        <el-form-item label="学制" prop="xuezhi">
          <el-input v-model="form.xuezhi" placeholder="请输入学制"/>
        </el-form-item>
        <el-form-item label="专项" prop="specialProject">
          <el-input v-model="form.specialProject" placeholder="请输入专项"/>
        </el-form-item>
        <el-form-item label="universityNameText" prop="universityNameText">
          <el-input v-model="form.universityNameText" placeholder="请输入universityNameText"/>
        </el-form-item>
        <el-form-item label="universityNameTextProcess" prop="universityNameTextProcess">
          <el-input v-model="form.universityNameTextProcess" placeholder="请输入universityNameTextProcess"/>
        </el-form-item>
        <el-form-item label="udid" prop="udid">
          <el-input v-model="form.udid" placeholder="请输入udid"/>
        </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-marjors :binding-plan="bindingPlan" :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 enrollColumns" :key="col.label" :label="col.prop">{{ col.label }}</el-checkbox>
      </el-checkbox-group>
    </el-dialog>
  </div>
</template>

<script>
import {
  listBusiWishUniversitySubmitRecruitPlan,
  getBusiWishUniversitySubmitRecruitPlan,
  delBusiWishUniversitySubmitRecruitPlan,
  addBusiWishUniversitySubmitRecruitPlan,
  updateBusiWishUniversitySubmitRecruitPlan,
  bindPlanEnrollMajor
} from "@/api/back/busiWishUniversitySubmitRecruitPlan";
import DynamicTable from "@/components/dynamic-table/index.vue";
import RecruitPlanEnrollMajorBinding from "@/views/back/components/RecruitPlanEnrollMajorBinding";
import BusiWishUniversitySubmitMarjors from "@/views/back/busiWishUniversitySubmitMarjors/index.vue";

export default {
  name: "BusiWishUniversitySubmitRecruitPlan",
  components: {BusiWishUniversitySubmitMarjors, DynamicTable},
  props: {
    bindingEnroll: {
      type: Object,
      default: () => ({})
    },
    bindingCopyFields: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 院校招生计划表格数据
      busiWishUniversitySubmitRecruitPlanList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        collegeCode: null,
        year: null,
        location: '湖南',
        batch: null,
        level: null,
        course: null,
        liberalScience: null,
        type: null,
        marjorId: null,
        universityId: null,
        universityCode: null,
        universityName: null,
        marjorCode: null,
        marjorName: null,
        marjorNameText: null,
        marjorBelongs: null,
        marjorDirection: null,
        createTime: null,
        status: null,
        planCount: null,
        planType: null,
        xuefei: null,
        xuezhi: null,
        specialProject: null,
        universityNameText: null,
        universityNameTextProcess: null,
        udid: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        year: [
          {required: true, message: "年份不能为空", trigger: "blur"}
        ],
        status: [
          {required: true, message: "状态(0:无效,1:有效)不能为空", trigger: "blur"}
        ],
        udid: [
          {required: true, message: "udid不能为空", trigger: "blur"}
        ]
      },
      // + add for new feature
      expandAll: true,
      // + add for bind enroll
      bindingTitle: '',
      bindingDialog: false,
      bindingPlan: null,
      bindingPlanRaw: null,
      bindingConfirm: true,
      bindingFields: ['location', 'universityCode', 'marjorName'],
      // some setting for binding
      bindingSetting: false
    };
  },
  computed: {
    isInDialog() {
      return this.bindingEnroll?.id
    },
    planColumns() {
      return [
        {
          type: 'selection',
          prop: 'selection',
          width: 55
        },
        ...RecruitPlanEnrollMajorBinding.sharedColumns,
        {
          prop: 'action',
          label: '操作',
          slotBody: 'action',
          width: 100
        },
        {
          type: 'expand',
          prop: 'expand',
          width: 40,
          slotBody: 'expand'
        }
      ]
    },
    enrollColumns() {
      return RecruitPlanEnrollMajorBinding.sharedColumns.filter(c => c.disableForEnroll !== true)
    }
  },
  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.bindingEnroll[key]
      })
    }
    this.getList();
  },
  methods: {
    // 展开操作
    handleExpandAll() {
      this.expandAll = !this.expandAll
      this._applyRowsExpand()
    },
    _applyRowsExpand() {
      this.busiWishUniversitySubmitRecruitPlanList.forEach(row => {
        this.$refs.table.tableCore.toggleRowExpansion(row, this.expandAll)
      })
    },
    handleToggleExpand(row) {
      this.$refs.table.tableCore.toggleRowExpansion(row)
    },
    /** 查询院校招生计划列表 */
    getList() {
      this.loading = true;
      listBusiWishUniversitySubmitRecruitPlan(this.queryParams).then(response => {
        response.rows.forEach(row => row.bindEnrollList = row.bindEnrollList || []) // safe init
        this.recalculateListWithBindList(response.rows)
        this.busiWishUniversitySubmitRecruitPlanList = 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,
        course: null,
        liberalScience: null,
        type: null,
        marjorId: null,
        universityId: null,
        universityCode: null,
        universityName: null,
        marjorCode: null,
        marjorName: null,
        marjorNameText: null,
        marjorBelongs: null,
        marjorDirection: null,
        createTime: null,
        status: 0,
        planCount: null,
        planType: null,
        xuefei: null,
        xuezhi: null,
        specialProject: null,
        universityNameText: null,
        universityNameTextProcess: null,
        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.resetEnrollBindPlan(selection)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加院校招生计划";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getBusiWishUniversitySubmitRecruitPlan(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) {
            updateBusiWishUniversitySubmitRecruitPlan(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBusiWishUniversitySubmitRecruitPlan(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 delBusiWishUniversitySubmitRecruitPlan(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('back/busiWishUniversitySubmitRecruitPlan/export', {
        ...this.queryParams
      }, `busiWishUniversitySubmitRecruitPlan_${new Date().getTime()}.xlsx`)
    },
    // + add for bind enroll
    handleBindOpen(row) {
      // deep clone row
      this.bindingPlan = JSON.parse(JSON.stringify(row))
      this.bindingPlanRaw = 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() {
      const oldBind = this.bindingPlanRaw.bindEnrollList.map(item => item.id)
      const newBind = this.bindingPlan.bindEnrollList.map(item => item.id)
      oldBind.sort((a, b) => a - b)
      newBind.sort((a, b) => a - b)
      if (oldBind.toString() == newBind.toString()) {
        this.$modal.msgWarning('未做任何修改')
        return
      }
      if (this.bindingConfirm) {
        const confirmMsg = `确认将${this.bindingPlan.marjorName}(${this.bindingPlan.id}) 与 [${newBind.toString()}] 共${newBind.length}项绑定？`
        await this.$modal.confirm(confirmMsg)
      }
      const data = {
        planId: this.bindingPlan.id,
        enrollIds: newBind
      }
      const res = await bindPlanEnrollMajor(data)
      this.$message.success(res.msg || '绑定成功')
      this.bindingDialog = false
      this.getList()
    },
    /* enroll list with selected */
    resetEnrollBindPlan(selection) {
      if (this.isInDialog) {
        this.bindingEnroll.bindPlan = selection
      }
    },
    recalculateListWithBindList(rows) {
      if (this.isInDialog) {
        // keep the new order of bind list
        const bindList = this.bindingEnroll.bindPlan.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.bindingEnroll.bindPlan = 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 => {
            console.log('toggleRowSelection', row)
            this.$refs.table.tableCore.toggleRowSelection(row, true)
          })
        }, 200)
      }
    }
  }
};
</script>

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