import React from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Button, Row, Col, Form, Input, Select, Checkbox, Modal, Transfer, Spin, Table, DatePicker, InputNumber, message, Upload, Icon } from 'antd';
import {
  extend,
  extendRule,
  initFilter,
  guid,
  extendGroupRule,
  initFilterGroup,
  extendInclude, getOnlyPropertyData
} from "../../../utils/common";
import config from "../../../config";
import storage from '../../../utils/storage';

const FormItem = Form.Item;
const Option = Select.Option;
const { TextArea } = Input;

class OG005ImportPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: {},
      selectedRowKeys: [],
    };
  };

  BtnClose = () => {
    if (typeof this.props.data.onCancel != "undefined" && typeof this.props.data.onCancel == 'function')
      this.props.data.onCancel();
  }
  componentDidMount() {
    if (this.props.data?.id) {
      this.props.form.resetFields();
      this.loadData(this.props.data?.id);

    }
  }
  getRequestHeaders = () => {
    // 请求参数
    const addHeader = 'Bearer ' + storage('lacal').getItem('accessToken').val
    const userId = storage('lacal').getItem('userid').val
    const user = storage('lacal').getItem('loginUserVerify').val
    const RootOrgId = storage('lacal').getItem('RootOrgId').val
    const orgId = storage('lacal').getItem('webOrgId').val
    const Tenant = storage('lacal').getItem('Tenant').val
    const headers = {
        Authorization: addHeader,
        userid: userId,
        username: user ? user.username : '',
        RootOrgId,
        orgId,
        Tenant: Tenant
    }
    return headers
}
  componentWillReceiveProps(NextProps) {
    if (NextProps.data?.id && this.props.data?.id != NextProps.data?.id) {
      this.loadData(NextProps.data?.id);
    }
  }
  componentWillReceiveProps(NextProps) {
    if (NextProps.custom.userImportClick) {
      this.props.form.resetFields();
      this.loadData();
      this.props.dispatch({
        type: 'custom/save',
        payload: {
          userImportClick: false
        },
      });
    }
  }

  loadData = () => {
    const { data, formId, login, dispatch } = this.props;
    const { id } = data ? data : {};

    this.setState({
      data: {},
      selectedRowKeys: [],
      updateLoadFileList: [],
    });
  };

  onSelectChange = (selectedRowKeys, selectedRows) => {  // 选择菜单行
    this.setState({ selectedRowKeys: selectedRowKeys });
  };

  handleOk = () => {
    const { form, dispatch, data } = this.props;
    const { getFieldValue, getFieldDecorator, validateFields, validateFieldsAndScroll, setFieldsValue } = form;
    validateFieldsAndScroll((errors, values) => {
      if (errors) return;
      let updateData = {};
      const details = [];
      var groupList = []
      if (this.state.data.Nav_AssessPlanItem) {
        this.state.data.Nav_AssessPlanItem.map(t => {
          let isSelect = false;
          if (this.state.selectedRowKeys && this.state.selectedRowKeys.length) {
            this.state.selectedRowKeys.forEach((n, i) => {
              if (t.ID == n) {
                isSelect = true;
              }
            });
          }
          if (!isSelect) return;
          var d = getOnlyPropertyData(t);
          details.push(d);

          if (groupList.length > 0) {
            let hasData = false
            groupList.map(g => {
              if (g.POST_NAME == d.POST_NAME && g.ANNUAL == d.ANNUAL && g.CYCLE_NAME == d.CYCLE_NAME) {
                hasData = true
              }
            })
            if (!hasData) {
              groupList.push({ POST_NAME: d.POST_NAME, ANNUAL: d.ANNUAL, CYCLE_NAME: d.CYCLE_NAME })
            }
          } else {
            groupList.push({ POST_NAME: d.POST_NAME, ANNUAL: d.ANNUAL, CYCLE_NAME: d.CYCLE_NAME })
          }
        });
      };
      if (!details.length) {
        message.error('请选择导入文件');
        return;
      }
      var ret = this.checkScore(details, groupList)
      if (ret) {
        updateData.Nav_AssessPlanItem = details;
        dispatch({
          type: 'app/getDataByPost',
          url: 'OG/OGSafeAssessPlanInput/SaveImportAssessPlan',
          payload: updateData,
          onComplete: (ret) => {
            if (ret) {
              if (data.close) {
                data.close();
              }
              this.setState({
                data: {},
                selectedRowKeys: [],
              });
              message.success('执行成功');
              this.BtnClose();
            }
          }
        });
      } else {
        message.error('被考核岗位，考核年度，考核周期相同的数据对应的标准分相加需为100分');
        return;
      }
    })
  };

  checkScore = (data, groupList) => {
    var ret = 0
    if (groupList.length > 0) {
      groupList.forEach(t => {
        var total = 0
        data.forEach(m => {
          if (m.POST_NAME == t.POST_NAME && m.ANNUAL == t.ANNUAL && m.CYCLE_NAME == t.CYCLE_NAME) {
            total = total + m.SCORE
          }
        })
        if (total != 100) {
          ret = -1
        }
      })
      return ret !== -1
    }
  }

  fillImportData = (ret) => {
    if (!ret) {
      this.setState({
        data: ret.Data,
        selectedRowKeys: [],
      })
    }
    if (ret.Data && ret.Data.MessageList && ret.Data.MessageList.length) {
      ret.Data.MessageList.forEach((n, i) => {
        message.warning(n);
      });
    }
    if (ret.ErrorMessage) {
      message.error(ret.ErrorMessage);
    }
    const selectedRowKeys = [];
    if (ret.Data && ret.Data.Nav_AssessPlanItem) {
      ret.Data && ret.Data.Nav_AssessPlanItem.forEach((n, i) => {
        selectedRowKeys.push(n.ID);
      });
    }
    this.setState({
      data: (ret.Data ? ret.Data : {}),
      selectedRowKeys
    });
  }

  render() {
    const { selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys: selectedRowKeys,
      fixed: false,
      columnWidth: 20,
      onChange: this.onSelectChange,
      hideDefaultSelections: false
    };
    const tableColumns = [
      { title: '被考核岗位', dataIndex: 'POST_NAME', key: 'POST_NAME' },
      { title: '考核年度', dataIndex: 'ANNUAL', key: 'ANNUAL' },
      { title: '考核周期', dataIndex: 'CYCLE', key: 'CYCLE' },
      { title: '考核项目', dataIndex: 'NAME', key: 'NAME' },
      { title: '标准分', dataIndex: 'SCORE', key: 'SCORE' },
      { title: '考核认定评分办法', dataIndex: 'METHOD', key: 'METHOD' },
    ];

    const that = this;
    const uploadProps = {
      name: 'file',
      action: config.serviceHost('api/OG/OGSafeAssessPlanInput/ImportAssessPlan'),
      data: { OrgId: this.props.login.OrgId },
      fileList: this.state.updateLoadFileList,
      accept: '.xls,.xlsx',
      headers: this.getRequestHeaders(),
      onChange(info) {
        that.setState({
          updateLoadFileList: info.fileList,
        });

        if (info.file.status === 'done') {
          that.fillImportData(info.file.response);
        } else if (info.file.status === 'error') {
          if (info.file.response && info.file.response.ErrorMessage) {
            message.error(`${info.file.name} 导入错误，详情：${info.file.response.ErrorMessage}`);
          }
          else {
            message.error(`${info.file.name} 导入错误`);
          }
        }
      },
    };


    return (
      <div>
        <Form>
          <Row style={{ marginTop: '10px' }}>
            <Upload {...uploadProps}>
              <Button>
                <Icon type="upload" /> 选择导入文件
              </Button>
            </Upload>
          </Row>
          <Row style={{ marginTop: '20px' }}>
            <Table
              rowKey="ID"
              pagination={false}
              dataSource={this.state.data.Nav_AssessPlanItem}
              columns={tableColumns}
              rowSelection={rowSelection}
            />
          </Row>
          <Row style={{ marginTop: '20px' }}>
            <Col style={{ textAlign: 'right' }}>
              <Button type={'primary'} icon={'save'} onClick={() => this.handleOk()}>保存</Button>
            </Col>
          </Row>
        </Form>
      </div>
    );
  }

}

export default connect(({ login, loading, custom }) => ({ login, loading, custom }))(Form.create()(OG005ImportPage));
