import React, { PureComponent } from 'react';
import { connect } from 'dva';
import style from 'styled-components';
import {
  // Tabs,
  // Select,
  Input,
  Button,
  message,
  Modal,
  // Icon,
  DatePicker,
  // Table,
  // List,
  // Card,
  Form,
  Radio,
  TreeSelect,
  // Checkbox,
  // Cascader,
  Row,
  Col,
  Breadcrumb
} from 'antd';
import moment from 'moment';
import "moment/locale/zh-cn";
import { checkMember } from '../../utils/utils';
import {
  getTreeperBydepart, //部门人员
  taskSalaryTempGetConfigSalaryType,
  taskSalaryTempGetComSalaryTempInfo, //查询企业薪酬模板详情
  taskSalaryTempSaveComSalaryTemp, //保存
  taskSalaryTempCheckSalaryTempPer //校验薪资模板人员
} from '../../services/api';

import './salarymanagement.less';

const { MonthPicker } = DatePicker;
const monthFormat = 'YYYY-MM';
// const { TabPane } = Tabs;
// const dateFormat = 'YYYY-MM-DD';
// const { confirm } = Modal;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
// const CheckboxGroup = Checkbox.Group;
// const { Option } = Select;
const { TextArea } = Input;
@connect(state => ({
  monitor: state.monitor
}))
@Form.create()
export default class Add extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      comSalaryTempId: this.props.match.params.comSalaryTempId,
      type: this.props.match.params.type,
      treeData: [], //人员数据
      salaryListArr: [], //模板配置
      visible: false, //过滤人员弹窗
      existsPerList: [], //过滤人员
      valuesSave: {}, //保存模板存放数据
      comSalaryTemp: {}, //编辑详情
      perList: [], //编辑人员选中详情
      taskPerArrayList: [], //不包含没有权限的人员的id
      taskPerArrayNoIdList: [] //只有没有权限的人员的id
    };
  }

  componentDidMount = () => {
    this.getTreeperBydepart();
    this.taskSalaryTempGetConfigSalaryType();
    this.taskSalaryTempGetComSalaryTempInfo();
  };

  /*********************ajax请求********************* */
  // 获取薪酬项目配置  新增
  taskSalaryTempGetConfigSalaryType = () => {
    if (this.state.comSalaryTempId === '00') {
      taskSalaryTempGetConfigSalaryType().then(
        response => {
          const resData = response.data;
          const tmp = resData.map(v => {
            return {
              categoryName: v.categoryName,
              salaryProjectList: v.salaryTypeList
            };
          });
          this.setState({ salaryListArr: tmp }, () => {
            console.log(this.state.salaryListArr, 'response');
          });
        },
        err => {
          console.log(err, 'err-获取薪酬项目配置');
        }
      );
    }
  };

  //查询企业薪酬模板详情  编辑
  taskSalaryTempGetComSalaryTempInfo = () => {
    if (this.state.comSalaryTempId !== '00') {
      console.log(this.state.comSalaryTempId);
      taskSalaryTempGetComSalaryTempInfo({
        comSalaryTempId: this.state.comSalaryTempId
      }).then(data => {
        console.log('查询企业薪酬模板详情', data);
        const resData = data.data;
        if (data.data) {
          this.setState({
            salaryListArr: resData.categoryList,
            comSalaryTemp: resData.comSalaryTemp,
            perList: resData.perList,
            taskPerArrayNoIdList: resData.perList //先把所有数据给他，之后在删除
          });

          if (this.state.treeData.length > 0) {
            //如果是组织机构先加载完，就在这里处理删除没有权限人员的id
            const perIdList = this.removeNOpowerId(
              this.state.perList,
              this.state.treeData
            );
            const { setFieldsValue } = this.props.form;
            setFieldsValue({
              perList: perIdList
            });
          }
        }
      });
    }
  };

  //部门人员
  getTreeperBydepart = () => {
    getTreeperBydepart().then(
      response => {
        console.log(response, 'response-部门人员-getTreeperBydepart');
        const responseData = checkMember(response.data);
        this.setState({ treeData: responseData });

        if (this.state.perList.length > 0) {
          //如果选择参与人员的数据先加载了，就在这里处理删除没有权限的人员id
          const treeData = JSON.parse(JSON.stringify(responseData));
          const perIdList = this.removeNOpowerId(this.state.perList, treeData);
          const { setFieldsValue } = this.props.form;
          setFieldsValue({
            perList: perIdList
          });
        }
      },
      err => {
        console.log(err, 'err-部门人员-getTreeperBydepart');
      }
    );
  };

  //删掉没有权限的人员id
  removeNOpowerId = (perList, treeData) => {
    treeData.map(item => {
      if (item.children && item.children.length > 0) {
        item.children = this.removeNOpowerId(perList, item.children);
      }
    });
    if (treeData.length > 0) {
      treeData.map(tdata => {
        perList.filter((item, i) => {
          if (item === tdata.key) {
            //给的人员id有在树结构里面
            this.state.taskPerArrayList.push(item);
            this.state.taskPerArrayNoIdList.splice(i, 1);
          }
        });
      });
    }
    console.log(this.state.taskPerArrayNoIdList);
    return this.state.taskPerArrayList;
  };

  taskSalaryTempSaveComSalaryTemp = values => {
    taskSalaryTempSaveComSalaryTemp(values).then(
      response => {
        console.log(response, '保存');
        this.props.history.push('/salarymanagement/template');
      },
      err => {
        console.log(err, 'err-保存');
      }
    );
  };

  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        console.log(values, 'values');

        if (this.state.taskPerArrayNoIdList.length > 0) {
          values.perList = values.perList.concat(
            this.state.taskPerArrayNoIdList
          );
        }

        if (!values.perList || values.perList.length === 0) {
          message.error('请选择参与人员');
          return;
        }

        if (values.perList.length > 1000) {
          message.error('选择人员最多1000人');
          return;
        }

        values.startYears = moment(values.startYears).format('YYYY-MM');
        values.endYears = moment(values.endYears).format('YYYY-MM');
        values.perList = values.perList.toString();

        if (values.startYears > values.endYears) {
          message.error('结束月份必须大于等于开始月份');
          return;
        }

        const checkPerObj = {
          startYears: values.startYears,
          endYears: values.endYears,
          perList: values.perList
        };

        // 编辑加comSalaryTempId
        if (this.state.comSalaryTempId !== '00') {
          values.comSalaryTempId = this.state.comSalaryTempId;
          checkPerObj.comSalaryTempId = this.state.comSalaryTempId;
        }

        //校验薪资模板人员,没有重复人员，直接保存，否则，弹框后再保存
        taskSalaryTempCheckSalaryTempPer(checkPerObj).then(
          response => {
            console.log(response, '校验薪资模板人员');
            const existsPerList = response.data.existsPerList;
            if (existsPerList.length === 0 || !existsPerList) {
              this.taskSalaryTempSaveComSalaryTemp(values);
            } else {
              this.setState({
                existsPerList,
                visible: true,
                valuesSave: values
              });
            }
          },
          err => {
            console.log(err, 'err-校验薪资模板人员');
          }
        );
      }
    });
  };

  // 校验人员
  handleCancel = () => {
    this.setState({
      visible: false
    });
  };
  handleOk = () => {
    const { valuesSave } = this.state;
    this.taskSalaryTempSaveComSalaryTemp(valuesSave);
    this.setState({
      visible: false
    });
  };

  //加载特殊字段薪酬
  renderSalaryList = () => {
    const { getFieldDecorator } = this.props.form;

    const formItemLayoutNew = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 12 }
      }
    };
    const formItemLayoutCheckBox = {
      labelCol: {
        xs: { span: 3 },
        sm: { span: 4 }
      },
      wrapperCol: {
        xs: { span: 12 },
        sm: { span: 12 },
        md: { span: 12 }
      }
    };
    const arr = this.state.salaryListArr.map((v, i) => {
      return (
        <div key={i} style={{ marginLeft: '12%' }}>
          <Row>
            <Col style={{ display: 'flex' }} xs={{ span: 16, offset: 0 }}>
              {v.categoryName}
            </Col>
          </Row>
          {v.salaryProjectList.map((value, index) => (
            <Row key={index} className='add-salary-box'>
              {value.isEdit === '1' && (
                <Col style={{ display: 'flex' }} xs={{ span: 24, offset: 0 }}>
                  <div
                    style={{ marginLeft: '0px' }}
                    className='hastitle-form not-five has-tips'
                  >
                    <FormItem label={value.salaryName} {...formItemLayoutNew}>
                      {getFieldDecorator(`${value.salaryType}_amount`, {
                        initialValue: value.setAmount,
                        rules: [
                          {
                            required: parseInt(value.isRequired, 10),
                            message: `${value.salaryName}`
                          },
                          {
                            pattern: /^[+]{0,1}(\d+)$/, //正整数
                            // pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, //支持小数金额
                            message: '请输入正整数金额!'
                          }
                        ]
                      })(
                        <Input
                          placeholder='金额'
                          // maxLength={6}
                          addonAfter={<span>{value.calUnit}</span>}
                        />
                      )}
                    </FormItem>
                    <Col style={{ marginBottom: '10px', color: '#EF4F21' }}>
                      {value.tips ? <div>{value.tips}</div> : ''}
                    </Col>
                  </div>
                  <div
                    style={{ marginLeft: '-30px' }}
                    className='hastitle-form has-tips'
                  >
                    <FormItem {...formItemLayoutNew}>
                      {getFieldDecorator(`${value.salaryType}_remark`, {
                        initialValue: value.remark ? value.remark : '',
                        rules: [
                          {
                            required: false,
                            message: '选填，工资单备注说明!'
                          }
                        ]
                      })(
                        <Input
                          placeholder='选填，工资单备注说明'
                          maxLength={50}
                          style={{ width: '200px' }}
                        />
                      )}
                    </FormItem>
                  </div>
                </Col>
              )}
              {value.isEdit === '0' && (
                <Col xs={{ span: 24, offset: 0 }}>
                  <div style={{ marginLeft: '0px' }} className='hastitle-form'>
                    <FormItem
                      label={value.salaryName}
                      {...formItemLayoutCheckBox}
                    >
                      {getFieldDecorator(`${value.salaryType}_five`, {
                        initialValue: '1',
                        rules: [
                          {
                            required: `${value.isRequired}`,
                            message: `${value.salaryName}`
                          }
                        ]
                      })(
                        // <Checkbox />
                        // <Select style={{ width: '200px' }}>
                        //   <Option value='1'>是</Option>
                        //   <Option value='0'>否</Option>
                        // </Select>
                        <RadioGroup>
                          <Radio value='1'>是</Radio>
                          {/* <Radio value='0'>否</Radio> */}
                        </RadioGroup>
                      )}
                    </FormItem>
                  </div>
                </Col>
              )}
            </Row>
          ))}
        </div>
      );
    });
    return arr;
  };

  /************************事件处理******************************************* */
  // 返回
  back = () => {
    this.props.history.push('/salarymanagement/template');
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { treeData, comSalaryTemp } = this.state;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 12 }
      }
    };
    return (
      <Container>
        <Breadcrumb
          style={{ borderBottom: '1px solid #E9E9E9', paddingBottom: '10px' }}
        >
          <Breadcrumb.Item>
            <a onClick={this.back}>薪酬模板管理</a>
          </Breadcrumb.Item>
          <Breadcrumb.Item>
            {this.state.comSalaryTempId === '00' && <span>新增薪酬模板</span>}
            {this.state.comSalaryTempId !== '00' && <span>编辑薪酬模板</span>}
          </Breadcrumb.Item>
        </Breadcrumb>
        <div className='check-salary'>
          <Form onSubmit={this.handleSubmit} style={{ marginTop: 40 }}>
            <FormItem {...formItemLayout} label='模板名称'>
              {getFieldDecorator('name', {
                initialValue: comSalaryTemp.name || '',
                rules: [
                  {
                    required: true,
                    message: '请输入职位名称!'
                  }
                ]
              })(<Input placeholder='请输入模板名称' maxLength={50} />)}
            </FormItem>
            <FormItem {...formItemLayout} label='开始月份'>
              {getFieldDecorator('startYears', {
                initialValue: comSalaryTemp.startYears
                  ? moment(comSalaryTemp.startYears, monthFormat)
                  : null,
                rules: [
                  {
                    required: true,
                    message: '请输入开始月份!'
                  }
                ]
              })(<MonthPicker placeholder='请选择开始月份' />)}
            </FormItem>
            <FormItem {...formItemLayout} label='结束月份'>
              {getFieldDecorator('endYears', {
                initialValue: comSalaryTemp.endYears
                  ? moment(comSalaryTemp.endYears, monthFormat)
                  : null,
                rules: [
                  {
                    required: true,
                    message: '请输入结束月份!'
                  }
                ]
              })(<MonthPicker placeholder='请选择结束月份' />)}
            </FormItem>
            <FormItem {...formItemLayout} label='备注'>
              {getFieldDecorator('remark', {
                initialValue: comSalaryTemp.remark || '',
                rules: [
                  {
                    required: false,
                    message: '备注!'
                  }
                ]
              })(
                <TextArea
                  className='margint'
                  autosize={{ minRows: 4, maxRows: 10 }}
                  maxLength={200}
                  placeholder='请输入备注'
                />
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={
                <span>
                  <span style={{ color: '#f5222d' }}>* </span>
                  <span>选择人员</span>
                </span>
              }
            >
              {getFieldDecorator('perList', {})(
                <TreeSelect
                  treeData={treeData}
                  treeCheckable
                  showCheckedStrategy={TreeSelect.SHOW_CHILD}
                  searchPlaceholder={'选择人员'}
                  maxTagCount={6}
                  // maxTagPlaceholder={'其他'}
                  // treeDefaultExpandAll
                  // allowClear
                />
              )}
            </FormItem>
            {/* <div>
              <Row>
                <Col style={{ display: 'flex' }} xs={{ span: 10, offset: 3 }}>
                  员工工资：
                </Col>
              </Row>
              <Row className='add-salary-box'>
                <Col style={{ display: 'flex' }} xs={{ span: 20, offset: 3 }}>
                  <FormItem {...formItemLayoutNew} label=''>
                    {getFieldDecorator('dsd', {
                      rules: [
                        {
                          required: false,
                          message: '基本工资!'
                        }
                      ]
                    })(<Checkbox />)}
                  </FormItem>
                  <div className='hastitle-form'>
                    <FormItem {...formItemLayoutNew} label='基本工资'>
                      {getFieldDecorator('444', {
                        rules: [
                          {
                            required: true,
                            message: '基本工资!'
                          }
                        ]
                      })(
                        <Input
                          placeholder='基本工资金额'
                          maxLength={50}
                          // width={600}
                          addonAfter={<span>元/月</span>}
                        />
                      )}
                    </FormItem>
                  </div>
                  <FormItem
                    style={{ width: '300px' }}
                    {...formItemLayoutNew}
                    label=''
                  >
                    {getFieldDecorator('ddfsd', {
                      rules: [
                        {
                          required: false,
                          message: '选填，工资单备注说明!'
                        }
                      ]
                    })(
                      <Input
                        placeholder='选填，工资单备注说明'
                        maxLength={50}
                        // width={600}
                      />
                    )}
                  </FormItem>
                </Col>
              </Row>
            </div> */}
            {/* 薪酬字段，动态加载 */}
            {this.renderSalaryList()}

            <FormItem {...formItemLayout} label=' ' colon={false}>
              <Button type='primary' onClick={this.back}>
                返回
              </Button>
              <Button
                type='primary'
                htmlType='submit'
                // onClick={this.setReleaseState.bind(this, 1)}
                style={{ marginLeft: 8 }}
              >
                保存
              </Button>
            </FormItem>
          </Form>
        </div>

        {/* 详情 */}
        <Modal
          title={`已有模板人员`}
          visible={this.state.visible}
          onCancel={this.handleCancel}
          onOk={this.handleOk}
          className='salary-detail'
          width={800}
          okText='过滤以上人员并继续保存'
          cancelText='取消'
        >
          <div>
            <p>
              有<span>{this.state.existsPerList.length}</span>
              人在该时段内已有模板，需先将其再旧模板中减去，再重新关联。
            </p>
            <p>
              <span>人员名单：</span>
              {this.state.existsPerList.join('、')}。
            </p>
          </div>
        </Modal>
      </Container>
    );
  }
}

const Container = style.div`
{
  padding:24px;
  .add-salary-box{
    .not-five{
      .ant-form-item-label{
        // text-align:left;
        width: 120px; 
      }
    }
  }
  .has-tips{
    .ant-form-item{
      margin-bottom:0px;
    }
  }
}
`;
