import React, {Component} from 'react';
import {connect} from 'dva';
import {Input, Button, Modal, Radio, Form, Checkbox, Table, Tabs} from 'antd';
import * as api from "../../../services/api";
import style from "styled-components";
import "./less/labor.less";


const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const { confirm } = Modal;
const { TabPane } = Tabs;

@connect(state => ({
  profile: state.profile,
}))

@Form.create()

export default class LaborNew extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      laborModal: false,//表头预览弹窗
      reportFieldsData: [],//报表表头请求数据集合
      checkData: {},//存储用户点击选择
      defaultChecks: [],
    }
  }

  /******************************生命周期******************************/

  componentDidMount = () => {
    this.enterpriseSalaryComReportReportFieldList();
  };

  /******************************ajax请求******************************/
    //请求表头字段集合
  enterpriseSalaryComReportReportFieldList = () => {
    api.enterpriseSalaryComReportReportFieldList({}).then(
      (data) => {
        this.setState({reportFieldsData: data.data});

        const defaultChecks = [...this.state.defaultChecks];
      },
      (err) => {
        console.log(err);
      });
  };
  //新建报表
  enterpriseSalaryComReportAddCompanyReport = (params) => {
    api.enterpriseSalaryComReportAddCompanyReport(params).then((data) => {
      // message.success(data.msg, 1.5, () => {
      //   this.props.history.push("/adminis/labor");
      // });
      const that = this;
      const reportId = data.data;
        confirm({
          title: "成功创建报表！",
          okText: '返回报表管理',
          cancelText:'马上编辑报表',
          onOk() {
            that.props.history.push('/adminis/labor');
          },
          onCancel() {
            that.props.history.push(`/adminis/reportUpdate/${reportId + ""}/${params.reportType}`);
          },
        });
    }, (err) => {
      console.log(err);
    });
  };

  /******************************相关事件******************************/

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let strArr = [];
        Object.keys(values).map((val, key) => {
          if (val.indexOf("reportFields") != -1) {
            values[val].map((v, k) => {
              let data = v.split("+");
              strArr.push(data[1]);
            });
          }
        });
        let str = strArr.join();
        let para = {
          remark: values.remark,
          reportType: values.reportType,
          reportName: values.reportName,
          reportFields: str,
        };
        this.enterpriseSalaryComReportAddCompanyReport(para);
      }
    });
  };

  onCheckChange = (value, type) => {
    const checkData = JSON.parse(JSON.stringify(this.state.checkData));
    checkData[type] = value;
    this.setState({checkData});
  };

  //预览表头
  previewHeader = () => {
    //从表单元素获取选中的 checkbox
    const checks = this.props.form.getFieldsValue();
    const columns = [];
    const dataSource = [{key: "info"}];//dataSource只有单条数据，这里手动指定。

    //动态创建  columns ，dataSource
     Object.keys(checks).map((val, key) => {
       if (val.indexOf("reportFields") !== -1) {
         checks[val].map((v, k) => {
           const [name, key, index, example] = v.split("+");
           columns.push({
             title: name,
             dataIndex: key,
             key: index
           });
           dataSource[0][key] = example;
         });
       }
     });


    //根据数据 请求的 seq 字段排序
    columns.sort((a, b) => parseInt(a.key) - parseInt(b.key));

    //根据表头列数返回配置
    const newProps = {columns: [...columns]};
    const length = columns.length;
    if (length < 5) {
      return;
    } else if (length > 5) {
      newProps.columns[0].fixed = "left";
      newProps.columns[0].width = 80;
      newProps.scroll = {x: 1300};
    } else if (length > 10) {
      //设置 table 部分 fixed 布局
      newProps.columns[0].width = 80;
      newProps.scroll = {x: 1500};
    }
    return <Table {...{dataSource, columns, pagination: false, ...newProps}} />;
  };

  handleMessageOk = () => {
    this.setState({
      laborModal: false,
    });
  };
  handleMessageCancel = () => {
    this.setState({
      laborModal: false,
    });
  };

  /******************************render******************************/
    //报表表头设置
  renderReportField = () => {
    const {getFieldDecorator} = this.props.form;
    const {reportFieldsData} = this.state;
    //  JSON.parse(JSON.stringify(this.state.reportFieldsData));
    const checkboxs = [];
    Object.keys(reportFieldsData).map((attr, index) => {
      const option = [];
      const defaultValue = [];
      reportFieldsData[attr].map(v => {
        option.push({
          value: v.fieldName + "+" + v.filedCode + "+" + v.seq + "+" + v.preview,
          label: v.fieldName,
          disabled: v.isRequired == "1"
        });
        if (v.isRequired == "1") {
          defaultValue.push(v.fieldName + "+" + v.filedCode + "+" + v.seq + "+" + v.preview);
        }
      });

      checkboxs.push(
        <FormItem
          label={attr}
          key={index}
        >
          {getFieldDecorator(`reportFields${index}`, {
            initialValue: defaultValue,
            rules: [{
              required: false, message: '请选择人员基本信息',
            }],
          })(
            <Checkbox.Group name="0"
                            onChange={(e) => {
                              this.onCheckChange(e, `reportFields${index}`)
                            }}
                            options={option}
            >
            </Checkbox.Group>
          )}
        </FormItem>
      );

    });
    return checkboxs;
  }

  render() {
    const {submitting} = this.props;
    const {getFieldDecorator} = this.props.form;

    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 8},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16},
      },
    };
    return (
      <div>
        <Form
          onSubmit={this.handleSubmit}
          style={{padding:'10px 24px 24px'}}
          className="header-form"
        >
        <Tabs>
          <TabPane tab="添加报表" key="1"/>
        </Tabs>
          {/* <h2 className="add-labor">添加报表</h2> */}
          <div className="labor-form">
            <FormItem
              {...formItemLayout}
              label="添加选项"
            >
              {getFieldDecorator('reportType', {
                  rules: [{
                    required: true, message: '添加选项不能为空！',
                  }],
                }
              )(
                <RadioGroup>
                  <Radio value="1">创建新的普通报表</Radio>
                  <Radio value="2">创建新的月度报表</Radio>
                </RadioGroup>
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="输入报表名称"
            >
              {getFieldDecorator('reportName', {
                rules: [{
                  required: true, message: '报表名称不能为空！',
                }],
              })(
                <Input placeholder="请输入报表名称，名称不超过25个字符" maxLength={25}/>
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="输入报表说明"
            >
              {getFieldDecorator('remark', {
                rules: [{
                  required: true, message: '报表说明不能为空！',
                }],
              })(
                <Input placeholder="请输入报表说明，说明不超过35个字符" maxLength={35}/>
              )}
            </FormItem>
          </div>
          <div className="labor_header">
            <h3>报表表头设置</h3>
            {this.renderReportField()}

            <Button type="primary" onClick={() => this.setState({laborModal: true})}
                    style={{marginLeft: '130px', marginBottom: '20px'}}>预览表头</Button>
          </div>
          <FormItem style={{marginTop: 32, marginLeft: 154}}>
            <Button onClick={()=>{
              this.props.history.push(`/adminis/labor`);
            }}>
              取消
            </Button>
            <Button type="primary" style={{marginLeft: 8}} htmlType="submit">保存</Button>
          </FormItem>
        </Form>
        <Modal
          width={1000}
          visible={this.state.laborModal}
          onOk={this.handleMessageOk}
          title={(<Title>预览表头</Title>)}
          onCancel={this.handleMessageCancel}
          closable={false}
          footer={null}
        >
          <div>
            {this.previewHeader()}
            <Button type="primary"
                    style={{display: "block", margin: "18px auto -6px"}}
                    onClick={() => this.setState({laborModal: false})}
            >确定</Button>
          </div>
        </Modal>
      </div>
    );
  }
}

const
  Title = style.div`{
    text - align:center;
    height:60px;
    line-height:60px;
    background: #F5F9FF;
    border-radius: 4px 4px 0 0;
    margin:-24px;
    padding:0 10px;
  }`;

