import React from 'react';
import { connect } from 'dva';
import localCfg from './localCfg';
import { message, } from 'antd';
import { Block, Page, Panel, Toolbar } from '@bizComponents';
import { formUtils } from '@utils';
import { routerRedux } from 'dva/router';
import { Loader, UploadEL } from '@components';

const EdDetail = ({ user, edDetail, dispatch, loading }) => {
  const { mode, list, formData, remoteCfg } = edDetail;
  const domain = 'edDetail';
  const { id, } = formData;
  const dataKey = id ? id : '';
  let readOnly = false;

  if (mode === 'view' || mode === 'approval') {
    readOnly = true;
  } else if (mode === 'update' || mode === 'create') {
    readOnly = false;
  }

  const formItemLayout = {
    colon: false,
    labelCol: {
      span: 4,
    },
    wrapperCol: {
      span: 20,
    },
    style: {},
  };

  const colProps = {
    xs: 22,
    sm: 22,
    md: 22,
    xl: 22,
  };

  const empTable = {
    rowKey: 'id',
    scroll: {
      x: '100%',
    },
    domain,
    dispatch,
    loading,
    enableSelection: !readOnly,
    dataSource: list,
    showAdd: !readOnly,
    showDelete: !readOnly,
    showCopy: false,
    size: 'small',
    readOnly,
  };

  const handleFormChange = (field) => {
    const key = Object.keys(field)[0];
    dispatch({
      type: `${domain}/updated`,
      payload: {
        key,
        value: field[key],
      },
    });
  };

  const handleSave = (submitted) => {

    if (list && list.length === 0) {
      message.error('请至少选择一个员工', 3);
      return 0;
    }

    if (list && list.length && formUtils.checkEmptyField(list, localCfg(formData, mode, dispatch, loading).empInfo) === true) {
      message.error('请输入成员信息的必填项', 3);
      return 0;
    }

    formUtils.validateForm([...localCfg(formData, mode, dispatch, loading).basicInfo,
    ...localCfg(formData, mode, dispatch, loading).problemDesc,
    ], formData, () => {
      dispatch({
        type: `${domain}/save`,
        payload: {
          submitted,
        },
      });
    });
  };

  const handleApprove = () => {
    dispatch({ type: `${domain}/approve` });
  };

  const handleReject = () => {
    dispatch({ type: `${domain}/reject` });
  };

  const handleContinued = () => {
    dispatch({ type: `${domain}/continued` });
  };

  const handleAdviceChange = (newValue) => {
    dispatch({
      type: `${domain}/updateState`,
      payload: { advice: newValue },
    });
  };

  if (remoteCfg) {



    remoteCfg.buttons.find(b => b.id === 'save')['onClick'] = () => {
      handleSave(false);
    };

    remoteCfg.buttons.find(b => b.id === 'submit')['onClick'] = () => {
      handleSave(true);
    };

    remoteCfg.buttons.find(b => b.id === 'approve')['onClick'] = () => {
      handleContinued();
    };

    remoteCfg.buttons.find(b => b.id === 'reject')['onClick'] = () => {
      handleReject();
    };

    remoteCfg.buttons.find(b => b.id === 'complete')['onClick'] = () => {
      handleApprove();
    };

    const buttons = [{
      id: 'advice',
      placeholder: '审批意见',
      hidden: mode !== 'approval',
      onChange: (e) => {
        handleAdviceChange(e.target.value);
      },
    },
    {
      id: 'claim',
      text: '发起索赔',
      type: 'primary',
      hidden: formData.roleName !== '技术质量部' || mode === 'create' || formData.hasClaimOrder,
      onClick: () => {
        if (formData.dutyType === '01') {
          dispatch(routerRedux.replace(`/cooperate/quality/co/create?8d=${formData.id}`));
        } else {
          message.error('只能对外部供应商发起索赔');
        }
      },
    }, {
      id: 'claimView',
      text: '查看索赔单',
      type: 'primary',
      hidden: mode === 'create' || !formData.hasClaimOrder,
      onClick: () => {
        if (formData.dutyType === '01') {
          dispatch(routerRedux.push(`/cooperate/quality/co?docNo8D=${formData.reportCode}`));
        } else {
          message.error('只能对外部供应商发起索赔');
        }
      },
    },
    ...remoteCfg.buttons,
    ];

    return (
      <div>
        <Toolbar prcId={formData.prcId} defId={formData.defId} loading={loading} record={formData} mode={mode} buttons={buttons}
          handleCancel={() => {
            dispatch({ type: `${domain}/cancel` });
          }}
        />

        <Page dispatch={dispatch} loading={loading} localCfg={localCfg} remoteCfg={remoteCfg} id="edDetail">

          <Panel id="base" title="基本信息">
            <Block id="basicInfo" type="form" data={formData} onFieldsChange={handleFormChange} />
          </Panel>

          <Panel id="emp" title="成员信息">
            <Block id="empInfo" type="table" mode={mode} data={list} {...empTable} />
          </Panel>

          <Panel id="flow" title="报告详情">
            <Block id="problemDesc" type="form" data={formData} onFieldsChange={handleFormChange}
              formItemLayout={formItemLayout} ColProps={colProps} />

            {mode !== 'create' ?
              <Block id="problemDescUpload" type="other" data={formData} mode={mode}>
                {formData.id &&<UploadEL api={`/api/8d/sfs/token?clsPath=PROBLEM_DESC&dataKey=${dataKey}`} dataKey={dataKey} listTypes={'text'} />}
              </Block> :
              <Block id="problemDescUpload" type="other"  data={formData} mode={mode}>
                <UploadEL api={`/api/8d/sfs/token?clsPath=PROBLEM_DESC&dataKey=${dataKey}`} dataKey={dataKey} listTypes={'text'} />
              </Block>
            }

            <Block id="tempPolicy" type="form" data={formData} onFieldsChange={handleFormChange}
              formItemLayout={formItemLayout} ColProps={colProps} />

            {mode !== 'create' ?
            <Block id="tempPolicyUpload" type="other">
              {formData.id &&<UploadEL api={`/api/8d/sfs/token?clsPath=TEMP_POLICY&dataKey=${dataKey}`} dataKey={dataKey} listTypes={'text'} />}
            </Block> :
            <Block id="tempPolicyUpload" type="other">
              <UploadEL api={`/api/8d/sfs/token?clsPath=TEMP_POLICY&dataKey=${dataKey}`} dataKey={dataKey} listTypes={'text'} />
            </Block>
            }

            <Block id="rootCause" type="form" data={formData} onFieldsChange={handleFormChange}
              formItemLayout={formItemLayout} ColProps={colProps} />

             {mode !== 'create' ?
            <Block id="rootCauseUpload" type="other">
              {formData.id && <UploadEL api={`/api/8d/sfs/token?clsPath=ROOT_CAUSE&dataKey=${dataKey}`} dataKey={dataKey} listTypes={'text'} />}
            </Block> :
            <Block id="rootCauseUpload" type="other">
              <UploadEL api={`/api/8d/sfs/token?clsPath=ROOT_CAUSE&dataKey=${dataKey}`} dataKey={dataKey} listTypes={'text'} />
            </Block>
             }


            <Block id="flowInfo" type="form" data={formData} onFieldsChange={handleFormChange}
              formItemLayout={formItemLayout} ColProps={colProps} />
          </Panel>
        </Page>
      </div>
    );
  } else {
    return <Loader fullScreen={false} spinning={loading.effects[`${domain}/query`]} />;
  }

};

export default connect(({ edDetail, loading }) => ({ edDetail, loading }))(EdDetail);
