<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="家长姓名" prop="parentName">
        <el-input
          v-model="queryParams.parentName"
          placeholder="请输入家长姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="家长电话" prop="parentPhone">
        <el-input
          v-model="queryParams.parentPhone"
          placeholder="请输入家长电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="关系" prop="relation">
        <el-select v-model="queryParams.relation" placeholder="请选择与学生的关系" clearable>
          <el-option
            v-for="dict in dict.type.parent_relation"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </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="['system:parent: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="['system:parent: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="['system:parent: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="['system:parent:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="parentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" />
      <el-table-column label="孩子" align="center" prop="studentIds" >
        <template slot-scope="scope">
					<dict-tag
						:options="dictTables.studentDict"
						:value="scope.row.studentIds"
					/>
				</template>
      </el-table-column>
      <el-table-column label="家长姓名" align="center" prop="parentName" />
      <el-table-column label="家长电话" align="center" prop="parentPhone" />
      <el-table-column label="与学生的关系" align="center" prop="relation">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.parent_relation" :value="scope.row.relation"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:parent:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:parent:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改家长管理对话框 -->
    <el-dialog 
      v-loading="formLoading"  
      element-loading-text="正在请求中..."
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      :title="title" 
      :visible.sync="open" 
      width="500px" 
      append-to-body
    >
      <el-form  ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="家长姓名" prop="parentName">
          <el-input v-model="form.parentName" placeholder="请输入家长姓名" />
        </el-form-item>
        <el-form-item label="家长电话" prop="parentPhone">
          <el-input v-model="form.parentPhone" placeholder="请输入家长电话" />
        </el-form-item>
        <el-form-item label="关联学生" prop="studentIds">
          <el-select 
            v-model="form.studentIds" 
            multiple
            filterable
            remote
            reserve-keyword
            placeholder="请输入学号关键字"
            :remote-method="studentRemoteMethod"
            :loading="studentSelectLoading"
            clearable 
            style="width: 100%;"
          >
              <el-option
                v-for="item in studentOptions"
                :key="item.id"
                :label="item.studentName"
                :value="item.id"
              >
                <span style="float: left">学号：{{ item.studentNum }}</span>
                <span style="float: right; color: #8492a6; font-size: 14px">姓名：{{ item.studentName }} </span>
              </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="与学生的关系" prop="relation">
            <el-select v-model="form.relation" placeholder="请选择与学生的关系" clearable style="width: 100%;">
              <el-option
                v-for="dict in dict.type.parent_relation"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
        </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>
  </div>
</template>

<script>
import { listParent, getParent, delParent, addParent, updateParent } from "@/api/system/parent";
import { listStudentAll } from "@/api/system/student";
import Textyixia from '@/mixin/Textyixia';
import { Loading } from 'element-ui';
export default {
  name: "Parent",
  mixins: [Textyixia],
  dicts: ['parent_relation'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 家长管理表格数据
      parentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        parentName: null,
        parentPhone: null,
        relation: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        studentIds: [
          { required: true, message: "学生不能为空", trigger: "change" }
        ],
        parentName: [
          { required: true, message: "家长姓名不能为空", trigger: "blur" }
        ],
        parentPhone: [
          { required: true, message: "家长电话不能为空", trigger: "blur" },
          { pattern: /^1[34578]\d{9}$/, message: "手机号码格式错误", trigger: "blur" }
        ],
        relation: [
          { required: true, message: "与学生的关系不能为空", trigger: "blur" }
        ],
      },
      dictTables: {
        studentDict: [],
			},
      studentList: [],
      studentOptions: [],
      studentSelectLoading: false,
      formLoading: true,
    };
  },
  created() {
    this.getList();
    this.dictTableData('tb_school_student,student_name,id').then(data => {
			this.dictTables.studentDict = data;
		});
  },
  methods: {
    /** 查询家长管理列表 */
    getList() {
      this.loading = true;
      listParent(this.queryParams).then(response => {
        this.parentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        studentId: null,
        parentName: null,
        parentPhone: null,
        relation: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.formLoading = true;
      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
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加家长";
      listStudentAll().then(res => {
        console.log(res);
        this.studentList = res.data
      }).finally(() => this.formLoading = false)
      
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      let loadingInstance = Loading.service({ fullscreen: true, background: 'rgba(0, 0, 0, 0.8)' });
      this.reset();
      const id = row.id || this.ids
      getParent(id).then(response => {
        this.form = response.data;
        console.log(this.form);
        this.form.studentIds = this.form.studentIds.split(',').map(Number);
        this.studentOptions = this.studentList.filter(item => response.data.studentIds.includes(item.id))
        this.title = "修改家长";
      }).finally(() => {
        
        setTimeout(() => {
          loadingInstance.close()
          this.open = true;
        }, 500)
      });
      listStudentAll().then(res => {
        console.log(res);
        this.studentList = res.data
      }).finally(() => {
        this.formLoading = false;
       
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.formLoading = true;
          addParent(this.form).then(response => {
              this.$modal.msgSuccess(this.form.id != null ? "修改成功" : '新增成功');
              this.open = false;
              this.getList();
          }).finally(() => this.formLoading = false);
          
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除家长管理编号为"' + ids + '"的数据项？').then(function() {
        return delParent(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/parent/export', {
        ...this.queryParams
      }, `parent_${new Date().getTime()}.xlsx`)
    },
    studentRemoteMethod(keyword) {
      this.studentOptions = this.studentList.filter(item => item.studentNum.includes(keyword))
    },
  }
};
</script>
