// 加载 React 相关组件
import React, { Component } from 'react';
// 加载 AntD 相关组件
import { Button, notification, Spin, Modal, Form, Input, Select } from 'antd';
// 加载自定义组件
import CommonTable from '../CommonTable';
// 加载自定义工具集
import { checkMapData } from '../../tools/Check';
// 加载 React-Redux 组件
import { connect } from 'react-redux';
// 加载 Actions
import {
  // 获取学院列表
  getCollegeList,
  getCollegeListSuccess,
  getCollegeListFailure,
  // 获取教学系列表
  getDepartmentList,
  getDepartmentListSuccess,
  getDepartmentListFailure,
  // 添加教学系
  addDepartmentData,
  addDepartmentDataSuccess,
  addDepartmentDataFailure,
  // 删除教学系
  delDepartmentData,
  delDepartmentDataSuccess,
  delDepartmentDataFailure,
  // 修改教学系
  editDepartmentData,
  editDepartmentDataSuccess,
  editDepartmentDataFailure,
} from '../../actions/Actions';

// 声明组件
let departmentTableTitle = null; // 声明教学系列表表头
let departmentTableColumns = null; // 声明教学系列表列定义
let departmentTableDataSource = []; // 声明教学系列表数据源

const FormItem = Form.Item;
const Option = Select.Option;
const confirm = Modal.confirm;

// 创建 DepartmentAdmin 组件
class DepartmentAdmin extends Component {
  // 自定义组件属性
  states = {
    loading: false, // 表明数据加载状态
  };
  // 自定义组件数据
  datas = {
    userData: null, // 缓存用户数据
    collegeList: null, // 缓存学院列表
    departmentData: null, // 缓存要修改的教学系数据
    departmentList: null, // 缓存教学系列表
  };
  // 构造方法
  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false, // 弹框显示状态
      modalTitle: '', // 弹框标题
      modalOnOk: () => { }, // 弹框"确认按钮"事件
      modalOnCancel: () => { }, // 弹框"取消按钮"事件
      collegeOptions: [], // 过滤后的学院列表
    };
  }
  // ------------------------------添加教学系相关方法------------------------------
  // 添加教学系方法
  handleAddDepartmentData() {
    this.openAddDepartmentDataModal();
  }
  // 打开添加教学系弹框
  openAddDepartmentDataModal() {
    this.setState({ // 初始化弹框
      modalVisible: true,
      modalTitle: '添加教学系',
      modalOnOk: this.handleConfirmAddDepartmentData.bind(this),
      modalOnCancel: this.handleCancelAddDepartmenData.bind(this),
    });
    const { setFieldsValue } = this.props.form;
    setFieldsValue({ // 初始化值
      department_no: '',
      college_name: '',
      department_name: '',
    });
  }
  // 关闭添加教学系弹框
  closeAddDepartmentDataModal() {
    this.setState({ modalVisible: false });
  }
  // 确认添加教学系按钮事件
  handleConfirmAddDepartmentData() {
    const { validateFields } = this.props.form;
    validateFields((error, values) => {
      if (!error) {
        this.props.addDepartmentData({
          user_role: 'admin',
          user_no: this.datas.userData['admin_no'],
          login_password: this.datas.userData['login_password'],
          add_type: 'department',
          add_data: {
            college_id: this.searchCollegeId(values['college_name']),
            department_no: values['department_no'],
            department_name: values['department_name'],
          },
        });
        this.closeAddDepartmentDataModal();
      }
    });
  }
  // 取消添加教学系按钮事件
  handleCancelAddDepartmenData() {
    this.closeAddDepartmentDataModal();
  }
  // ------------------------------修改教学系相关方法------------------------------
  // 修改教学系方法
  handleEditDepartmentData(text, record, index) {
    this.openEditDepartmentDataModal(record);
  }
  // 打开修改教学系弹框
  openEditDepartmentDataModal(record) {
    this.setState({ // 初始化弹框
      modalVisible: true,
      modalTitle: '修改教学系',
      modalOnOk: this.handleConfirmEditDepartmentData.bind(this),
      modalOnCancel: this.handleCancelEditDepartmenData.bind(this),
    });
    const { setFieldsValue } = this.props.form;
    setFieldsValue({ // 初始化值
      department_no: record['department_no'],
      college_name: record['college_name'],
      department_name: record['department_name'],
    });
    this.datas.departmentData = record;
  }
  // 关闭修改教学系弹框
  closeEditDepartmentDataModal() {
    this.setState({ modalVisible: false });
  }
  // 确认修改教学系按钮事件
  handleConfirmEditDepartmentData() {
    const { validateFields } = this.props.form;
    validateFields((error, values) => {
      if (!error) {
        this.props.editDepartmentData({
          user_role: 'admin',
          user_no: this.datas.userData['admin_no'],
          login_password: this.datas.userData['login_password'],
          edit_type: 'department',
          edit_data: {
            department_id: this.datas.departmentData['department_id'],
            college_id: this.searchCollegeId(values['college_name']),
            department_name: values['department_name'],
          },
        });
        this.closeEditDepartmentDataModal();
      }
    });
  }
  // 取消修改教学系按钮事件
  handleCancelEditDepartmenData() {
    this.closeEditDepartmentDataModal();
  }
  // ------------------------------删除教学系相关方法------------------------------
  // 删除教学系方法
  handleDeleteDepartmentData(text, record, index) {
    let delDepartmentData = this.props.delDepartmentData;
    let requestParams = {
      user_role: 'admin',
      user_no: this.datas.userData['admin_no'],
      login_password: this.datas.userData['login_password'],
      del_type: 'department',
      del_id: record['department_id'],
    };
    confirm({
      title: `确定删除"${record['department_name']}"吗？`,
      onOk() {
        delDepartmentData(requestParams);
      },
    });
  }
  // -----------------------------------其他方法-----------------------------------
  // 过滤学院列表方法
  filterCollegeList(collegeName) {
    let collegeOptions = [];
    this.datas.collegeList.forEach((item, index) => {
      if (item['college_name'].indexOf(collegeName) !== -1) {
        collegeOptions.push(<Option key={index} value={item['college_name']}>{item['college_name']}</Option>);
      }
    });
    this.setState({ collegeOptions: collegeOptions });
  }
  // 查找学院ID方法
  searchCollegeId(collegeName) {
    let collegeList = this.datas.collegeList;
    let length = collegeList.length;
    for (let i = 0; i < length; i++) {
      let item = collegeList[i];
      if (item['college_name'] === collegeName) {
        return item['college_id'];
      }
    }
    return -1;
  }
  // -----------------------------------------------------------------------------
  // 组件加载预处理方法
  componentWillMount() {
    departmentTableTitle = ( // 初始化列表表头
      <div className='table-title'>
        <div className='table-title-left'><h2>教学系管理</h2></div>
        <div className='table-title-right'>
          <Button
            type='primary'
            icon='plus'
            onClick={this.handleAddDepartmentData.bind(this)}>手动添加</Button>
        </div>
      </div>
    );
    departmentTableColumns = [{ // 初始化列定义
      title: '教学系编号',
      dataIndex: 'department_no',
      key: 'department_no',
    }, {
      title: '教学系名称',
      dataIndex: 'department_name',
      key: 'department_name',
    }, {
      title: '所属学院',
      dataIndex: 'college_name',
      key: 'college_name',
    }, {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      width: 260,
      render: (text, record, index) => {
        return (
          <div>
            <Button
              style={{ marginRight: 10 }}
              type='primary'
              icon='edit'
              onClick={this.handleEditDepartmentData.bind(this, text, record, index)}>修改教学系</Button>
            <Button
              type='primary'
              icon='delete'
              onClick={this.handleDeleteDepartmentData.bind(this, text, record, index)}>删除教学系</Button>
          </div>
        )
      }
    }];
    const { mapUserData } = this.props.actions; // 初始化用户数据
    if (checkMapData(mapUserData)) {
      this.datas.userData = mapUserData.data; // 缓存用户数据
    }
  }
  // 组件加载后处理方法
  componentDidMount() {
    this.props.getCollegeList(
      this.datas.userData['admin_no'],
      this.datas.userData['login_password']
    );
    this.props.getDepartmentList(
      this.datas.userData['admin_no'],
      this.datas.userData['login_password']
    );
    this.states.loading = true;
  }
  // 组件接受新属性处理方法
  componentWillReceiveProps(newProps) {
    const { mapCollegeList, mapDepartmentList } = newProps.actions;
    if (checkMapData(mapCollegeList) && checkMapData(mapDepartmentList)) {
      this.datas.collegeList = mapCollegeList.data; // 缓存学院列表数据
      this.datas.departmentList = mapDepartmentList.data; // 缓存教学系列表数据
      this.states.loading = false; // 修改数据加载状态
      if (!this.state.modalVisible) {
        departmentTableDataSource = [];
        this.datas.departmentList.forEach((item, index) => {
          let departmentObject = {};
          departmentObject['key'] = index;
          departmentObject['department_id'] = item['department_id'];
          departmentObject['department_no'] = item['department_no'];
          departmentObject['department_name'] = item['department_name'];
          departmentObject['college_id'] = item['college_id'];
          departmentObject['college_name'] = item['college_name'];
          departmentTableDataSource.push(departmentObject);
        });
      }
    } else {
      this.states.loading = true; // 修改数据加载状态
    }
  }
  // 组件渲染方法
  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <div className="department-admin">
        {/*教学系列表*/}
        <Spin spinning={this.states.loading} tip='数据加载中 ...' size='large'>
          <CommonTable
            title={() => departmentTableTitle}
            columns={departmentTableColumns}
            dataSource={departmentTableDataSource} />
        </Spin>
        {/*添加、修改教学系弹框*/}
        <Modal
          title={this.state.modalTitle}
          visible={this.state.modalVisible}
          onOk={this.state.modalOnOk}
          onCancel={this.state.modalOnCancel}
        >
          <Form className='common-form'>
            <FormItem className='common-form-item'>
              <span>请输入教学系编号（没有请填“无”）：</span>
              {getFieldDecorator('department_no', {
                rules: [{ required: true, message: '请输入教学系编号' }],
                initialValue: ''
              })(
                <Input
                  type='text'
                  size='large'
                  disabled={this.state.modalTitle === '修改教学系' ? true : false}
                  placeholder='请输入教学系编号' />
                )}
            </FormItem>
            <FormItem className='common-form-item'>
              <span>请输入教学系所属学院：</span>
              {getFieldDecorator('college_name', {
                rules: [{ required: true, message: '请输入教学系所属学院' }],
                initialValue: ''
              })(
                <Select
                  className="select"
                  getPopupContainer={() => document.querySelector('.select')}
                  mode="combobox"
                  placeholder="请输入教学系所属学院"
                  defaultActiveFirstOption={false}
                  showArrow={false}
                  filterOption={false}
                  onChange={this.filterCollegeList.bind(this)}>{this.state.collegeOptions}</Select>
                )}
            </FormItem>
            <FormItem className='common-form-item'>
              <span>请输入教学系名称：</span>
              {getFieldDecorator('department_name', {
                rules: [{ required: true, message: '请输入教学系名称' }],
                initialValue: ''
              })(
                <Input
                  type='text'
                  size='large'
                  placeholder='请输入教学系名称' />
                )}
            </FormItem>
          </Form>
        </Modal>
      </div>
    )
  }
}

// 声明待绑定的状态
const mapStateToProps = (store) => {
  return {
    actions: store.actionsState
  }
}

// 声明待绑定的方法
const mapDispatchToProps = (dispatch) => {
  let mapFunction = {
    // 获取学院列表
    getCollegeList: (adminNo, loginPassword) => {
      dispatch(getCollegeList('admin', adminNo, loginPassword)).mapCollegeList.then((response) => {
        let resData = response.data;
        if (resData.errorCode === 0) {
          dispatch(getCollegeListSuccess(resData.data));
          notification['success']({
            message: '获取学院列表成功',
            duration: 4.5,
          });
        } else {
          dispatch(getCollegeListFailure(resData));
          notification['error']({
            message: '获取学院列表失败',
            description: resData.errorMessage,
            duration: 4.5,
          });
        }
      });
    },
    // 获取教学系列表
    getDepartmentList: (amdinNo, loginPassword) => {
      dispatch(getDepartmentList('admin', amdinNo, loginPassword)).mapDepartmentList.then((response) => {
        let resData = response.data;
        if (resData.errorCode === 0) {
          dispatch(getDepartmentListSuccess(resData.data));
          notification['success']({
            message: '获取教学系列表成功',
            duration: 4.5,
          });
        } else {
          dispatch(getDepartmentListFailure(resData));
          notification['error']({
            message: '获取教学系列表失败',
            description: resData.errorMessage,
            duration: 4.5,
          });
        }
      });
    },
    // 添加教学系
    addDepartmentData: (requestParams) => {
      dispatch(addDepartmentData(requestParams)).mapAddDepartmentData.then((response) => {
        let resData = response.data;
        if (resData.errorCode === 0) {
          dispatch(addDepartmentDataSuccess(resData));
          notification['success']({
            message: '添加教学系成功',
            duration: 4.5,
          });
          mapFunction.getDepartmentList(requestParams['user_no'], requestParams['login_password']);
        } else {
          dispatch(addDepartmentDataFailure(resData));
          notification['error']({
            message: '添加教学系失败',
            description: resData.errorMessage,
            duration: 4.5,
          });
        }
      });
    },
    // 删除教学系
    delDepartmentData: (requestParams) => {
      dispatch(delDepartmentData(requestParams)).mapDelDepartmentData.then((response) => {
        let resData = response.data;
        if (resData.errorCode === 0) {
          dispatch(delDepartmentDataSuccess(resData));
          notification['success']({
            message: '删除教学系成功',
            duration: 4.5,
          });
          mapFunction.getDepartmentList(requestParams['user_no'], requestParams['login_password']);
        } else {
          dispatch(delDepartmentDataFailure(resData));
          notification['error']({
            message: '删除教学系失败',
            description: resData.errorMessage,
            duration: 4.5,
          });
        }
      });
    },
    // 修改教学系
    editDepartmentData: (requestParams) => {
      dispatch(editDepartmentData(requestParams)).mapEditDepartmentData.then((response) => {
        let resData = response.data;
        if (resData.errorCode === 0) {
          dispatch(editDepartmentDataSuccess(resData));
          notification['success']({
            message: '修改教学系成功',
            duration: 4.5,
          });
          mapFunction.getDepartmentList(requestParams['user_no'], requestParams['login_password']);
        } else {
          dispatch(editDepartmentDataFailure(resData));
          notification['error']({
            message: '修改教学系失败',
            description: resData.errorMessage,
            duration: 4.5,
          });
        }
      });
    },
  };
  return mapFunction;
}

// 导出组件
export default connect(mapStateToProps, mapDispatchToProps)(Form.create()(DepartmentAdmin));
