import React from 'react';
import { connect } from 'dva';
import { Button, Row, Col, Form, Input,Select,Checkbox,Modal,Transfer,Spin ,Table,Tabs,Popconfirm,message} from 'antd';
import {
  extend,
  extendRule,
  initFilter,
  initQueryFilter,
  getOnlyPropertyData,
  extendInclude,
  getDataFieldValue, guid, initFilterGroup, extendGroupRule
} from "../../../utils/common";
import FormPage from '../../FormPage';

const FormItem = Form.Item;
const Option = Select.Option;
const TabPane = Tabs.TabPane;
const { TextArea } = Input;
class FlowPermitEditPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: {},
      btns:[],
      title:'流程审核',
      historyData:[],
      remark:'',
    };
  };

  componentDidMount() {
    this.props.form.resetFields();
    this.loadData();
  }

  componentWillReceiveProps(NextProps) {
    const {data}=this.props;
    let {id}=data?data:{};
    if(!id)
      id='';
    if (NextProps.custom['flowPermitEdit'+id] ) {
      this.props.form.resetFields();
      this.loadData();
      this.props.dispatch({
        type: 'custom/save',
        payload: {
          ['flowPermitEdit'+id]:false
        },
      });
    }
  }

  loadData=()=> {
    const {data,formId,login,dispatch}=this.props;
    const {id}=data?data:{};
    if(id){
      const json = initFilter(this.props.login.OrgId);
      extendRule(json, 'ID', 1, id);
      extendInclude(json,'Form');
      this.props.dispatch({
        type: 'PFFlowPermitEdit/getFlow',
        payload: json,
        onComplete: (ret) => {
          if(ret){
            this.setState({
              data: ret,
            });
          }
        }
      });

      const historyJson = initFilter(this.props.login.OrgId,'','CREATE_TIME',1);
      extendRule(historyJson, 'InstanceId', 1, id);
      this.props.dispatch({
        type: 'PFFlowPermitEdit/getOperHistoryList',
        payload: historyJson,
        onComplete: (ret) => {
          this.setState({
            historyData: ret,
          });
        }
      });
    }


    if(formId){
      const btnJson = initFilter(this.props.login.OrgId,'','NUM',0);
      extendRule(btnJson, 'PAGE_CUSTOM_FORM_ID', 1, formId);
      this.props.dispatch({
        type: 'PFFlowPermitEdit/getBtnList',
        payload: btnJson,
        onComplete: (ret) => {
          if(ret){
            this.setState({
              btns: ret,
            });
          }
        }
      });
    }
  };


  getBtns=()=>{
    const isShow=this.props.data?this.props.data.isShow:false;
    if(isShow)return;
    if(this.state.btns){
      return this.state.btns.map(item=>{
        if(item.BTN_TYPE==7) {
          if (item.CLICK_EVENT == 'agree') {//同意
            return <Popconfirm title="是否确定审核通过?" key={item.ID} onConfirm={() => this.handleOk("1")}>
              <Button type={item.CSS} icon={item.ICON} style={{'margin-left': '10px'}} key={item.ID}>{item.LABEL}</Button>
            </Popconfirm>;
          }
          else if (item.CLICK_EVENT == 'reject') {//驳回
            return <Popconfirm title="是否确定审核驳回?" key={item.ID} onConfirm={() => this.handleOk("3")}>
              <Button type={item.CSS} icon={item.ICON} style={{'margin-left': '10px'}} key={item.ID}>{item.LABEL}</Button>
            </Popconfirm>;
          }
          else if (item.CLICK_EVENT == 'disagree') {//不同意
            return <Popconfirm title="是否确定审核不通过?" key={item.ID} onConfirm={() => this.handleOk("2")}>
              <Button type={item.CSS} icon={item.ICON} style={{'margin-left': '10px'}} key={item.ID}>{item.LABEL}</Button>
            </Popconfirm>;

          }

        }
      });
    }
  };

  handleOk = (flag) => {
    const {form,dispatch,data} = this.props;
    const {getFieldValue, getFieldDecorator, validateFields, validateFieldsAndScroll, setFieldsValue} = form;
    validateFieldsAndScroll((errors, values) => {
      if (errors) return;
      const updateData={
        FlowInstanceId:this.state.data.ID,
        VerificationOpinion:this.state.remark,
        VerificationFinally:flag,
        UserId:this.props.login.userId,
        UserName:this.props.login.user.NAME,
      };
      dispatch({
        type: 'PFFlowPermitEdit/permitFlow',
        payload: updateData,
        onComplete: (ret) => {
          if(ret) {
            if(this.state.saveFunc) {
              this.state.saveFunc();
            }
            else{
              this.handleClose();
            };
          }
        }
      });
    });
  };

  handleClose=()=> {
    const {form, dispatch, data} = this.props;
    if (data.close) {
      data.close();
    }
    message.success('执行成功');
  };


  handleRegSave=(saveFunc)=>{
    this.setState({
      saveFunc:saveFunc,
    });
  };



  showBillData=()=>{
    if(this.state.data&&this.state.data.EntityId&&this.state.data.Form&&this.state.data.Form.CODE) {
      const isShow=this.props.data?this.props.data.isShow:false;
      const data = {
        id: this.state.data.EntityId,
        isShow:isShow,// this.state.data.ActivityEditable == 0,
        isPermit: !isShow,//this.state.data.ActivityEditable == 1,
      };
      if(data.isPermit){//为审核才注册
        data.onRegSaveFunc=this.handleRegSave;
        data.onCancel=this.handleClose;
      };
      return <FormPage formCode={this.state.data.Form.CODE} data={data} />
    };
  };

  render() {
    const {form, location, dispatch, match,loading} = this.props;
    const {getFieldValue, getFieldDecorator, validateFields, validateFieldsAndScroll, setFieldsValue} = form;
    const {data}=this.state;
    console.log(data);
    const isShow=this.props.data?this.props.data.isShow:false;
    const tableColumns=[
      {title: '审核人', dataIndex: 'CreateUserName', key: 'CreateUserName'},
      {title: '审核时间', dataIndex: 'CreateDate', key: 'CreateDate'},
      {title: '审核结果', dataIndex: 'Content', key: 'Content'},
    ]

    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 14},
    };

    const onChangeRemark=(e)=>{
      this.setState({
        remark:e.target.value,
      });
    }

    const onChangeTabKey=(actionKey)=>{
      if(actionKey=='2'){
        if(this.state.data.FrmId) {
          this.props.dispatch({
            type: 'editPage/save',
            payload: {
              [this.state.data.FrmId + '_reload']: true
            },
          });
        }
      }
    };

    return (
      <div>
        <div>
          <h2>{this.state.title}</h2>
        </div>
        <Form>
          <Row style={{ marginTop: '20px' }}>
            <Col span={12}>
              <Form.Item
                label={'标题'}
                {...formItemLayout}
              >
                {getFieldDecorator('CustomName', {
                  validateTrigger: 'onBlur',
                  initialValue: getDataFieldValue(data,'CustomName'),
                })(<Input disabled={true} />)}
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={'送审单号'}
                {...formItemLayout}
              >
                {getFieldDecorator('Code', {
                  initialValue:  getDataFieldValue(data,'Code'),
                })(<Input disabled={true} />)}
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={'申请人'}
                {...formItemLayout}
              >
                {getFieldDecorator('CreateUserName', {
                  initialValue:  getDataFieldValue(data,'CreateUserName'),
                })(<Input disabled={true} />)}
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={'申请时间'}
                {...formItemLayout}
              >
                {getFieldDecorator('CreateDate', {
                  initialValue:  getDataFieldValue(data,'CreateDate'),
                })(<Input disabled={true} />)}
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={'当前节点'}
                {...formItemLayout}
              >
                {getFieldDecorator('ActivityName', {
                  initialValue:  getDataFieldValue(data,'ActivityName'),
                })(<Input disabled={true} />)}
              </Form.Item>
            </Col>

            <Col span={12}>
              <Form.Item
                label={'审核备注'}
                {...formItemLayout}
              >
                {getFieldDecorator('REMARK', {
                })(<TextArea rows={4} placeholder={'请输入备注'} onChange={onChangeRemark} disabled={isShow} />)}
              </Form.Item>
            </Col>
          </Row>

          <Row style={{ marginTop: '20px' }}>
            <Col style={{ textAlign: 'right' }}>
              {
                this.getBtns()
              }

            </Col>
          </Row>
          <Row style={{ marginTop: '20px' }}>
            <Tabs defaultActiveKey="1" onChange={onChangeTabKey}>
            <TabPane tab="流程详情" key="1">
               <FormPage formCode={'PF044'} data={{id:this.props.data.id}}/>  
              </TabPane>
              <TabPane tab="审核日志" key="2">
                <Table
                  rowKey="ID"
                  pagination={false}
                  dataSource={this.state.historyData}
                  columns={tableColumns}
                />

              </TabPane>
              <TabPane tab="单据数据" key="3">
                {
                  this.showBillData()
                }
              </TabPane>
            </Tabs>
          </Row>

        </Form>
      </div>
    );
  }

}

FlowPermitEditPage.propTypes = {
};

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