import { Block, Page, Panel, Toolbar } from '@bizComponents';
import { enums, formUtils } from '@utils';
import { message, Card } from 'antd';
import { connect } from 'dva';
import React from 'react';
import { Loader, UploadEL, CollapseEL } from '../../../components';
import config from './contractDetailCfg';

const Detail = ({ user, contractDetail, dispatch, loading }) => {
  const {
    remoteCfg,
    readOnly,
    formData,
    mode,
    list,
    total,
    inputList,
    attachRepo,
    saveBtnFlag,
    previewBtnFlag,
    AFlag,
    suppFlag,
    sealUploadFlag,
    attachRepoTmpl,
    dataKeyTmpl
  } = contractDetail;
  const domain = 'contractDetail';
  const domainCN = '合同明细';

  const { customMsg, stampAttachRepo } = enums;
  const variate = {
    rowKey: 'contractVarId',
    scroll: {
      x: '100%'
    },
    domain,
    dispatch,
    loading,
    showDelete: false,
    showAdd: false,
    showCopy: false,
    enableSelection: false,
    showColumn: false,
    size: 'small'
  };

  // 条款内容
  const contractTmplTableProps = {
    rowKey: 'id',
    scroll: {
      x: '100%'
    },
    domain,
    dispatch,
    loading,
    showAdd: !readOnly || formData.taskKey === 'initiator',
    showDelete: !readOnly || formData.taskKey === 'initiator',
    showCopy: false
  };

  const handleBeforeUploadFile = file => {
    if (file.name.indexOf(formData.contractName) === 0) {
      return true;
    } else {
      message.warn('盖章合同附件与合同名称不符');
      return false;
    }
  };

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

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

  const handlePrint = () => {
    dispatch({ type: `${domain}/print`, payload: { formData } });
  };

  const handleSubmitAgain = () => {
    dispatch({ type: `${domain}/submitAgain` });
  };

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

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

  const handleSave = submitted => {
    formUtils.validateForm(
      [
        ...config(formData, mode, dispatch, loading, {}).contractBasicForm,
        ...config(formData, mode, dispatch, loading, {}).contractTmplForm
      ],
      formData,
      () => {
        if (inputList.length === 0) {
          message.warn('至少需要一个模板变量');
          return;
        }
        let count = 0;
        const checkVars = inputList.filter(i => i.settled);
        checkVars.forEach(item => {
          if (!item.itemContent) {
            message.warn(
              customMsg.CONTRACT_ITEM_CONTENT +
                item.contractVarDesc +
                customMsg.CONTRACT_CHECK_NULL
            );
            return;
          }
          if (item.itemContent && item.itemContent.length > 500) {
            message.warn(
              customMsg.CONTRACT_ITEM_CONTENT +
                item.contractVarDesc +
                customMsg.CONTRACT_ITEM_CONTENT_CHECK_LENGTH
            );
            return;
          }
          count += 1;
        });
        if (count === checkVars.length) {
          let agreements = 0;
          if (list!=null && list.length>0){
            list.forEach(item => {
              if (!item.lineNo) {
                agreements++;
              }
              if (!item.itemContent) {
                agreements++;
              }
            });
          }
          if (agreements === 0) {
            dispatch({
              type: `${domain}/save`,
              payload: {
                submitted: submitted !== true ? false : submitted
              }
            });
          } else {
            message.warn("补充条款内容 必填");
          }
        } else {
          message.warn(
            customMsg.CONTRACT_ITEM_CONTENT +
              customMsg.CONTRACT_ITEM_CONTENT_VAL +
              customMsg.CONTRACT_CHECK_FAIL
          );
        }
      }
    );
  };
  if (remoteCfg) {
    remoteCfg.buttons.find(b => b.id === 'approve').onClick = () => {
      handleApprove();
    };

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

    remoteCfg.buttons.find(b => b.id === 'notice').onClick = () => {
      // dispatch({ type: `${domain}/notice` });
    };

    const buttons = [
      {
        id: 'advice',
        placeholder: '审批意见',
        hidden: mode !== 'approval',
        onChange: e => {
          dispatch({
            type: `${domain}/updateState`,
            payload: { advice: e.target.value }
          });
        }
      },
      {
        id: 'save',
        text: '保存',
        type: 'primary',
        hidden: saveBtnFlag ? mode === 'view' || mode === 'approval' : true,
        onClick: () => {
          handleSave(false);
        }
      },
      {
        id: 'submit',
        text: '提交',
        type: 'primary',
        hidden: saveBtnFlag ? mode === 'view' || mode === 'approval' : true,
        onClick: () => {
          handleSave(true);
        }
      },
      {
        id: 'preview',
        text: '预览',
        type: 'primary',
        hidden: previewBtnFlag ? mode === 'create' : true,
        onClick: handlePrint
      },
      {
        id: 'submitAgain',
        text: '提交',
        type: 'primary',
        hidden: saveBtnFlag
          ? mode !== 'approval' || formData.taskKey !== 'initiator'
          : true,
        onClick: handleSubmitAgain
      },
      ...remoteCfg.buttons
    ];

    return (
      <div style={{ height: '100%' }}>
        <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={config}
          remoteCfg={remoteCfg}
          id="contractDetails"
        >
          <Panel id="contractBasic" title="基础信息">
            <Block
              id="contractBasicForm"
              type="form"
              data={formData}
              onFieldsChange={handleFormChange}
              mode={mode}
              extraInfo={{ AFlag: AFlag }}
            />
          </Panel>

          <Panel id="contractTmpl" title="合同模板" isOpened={false} hidden={suppFlag}>
            <Block
              id="contractTmplForm"
              type="form"
              data={formData}
              onFieldsChange={handleTmplChange}
            />
          </Panel>

          <Panel id="contractVariate" title="模板变量" isOpened={false}>
            <Block
              id="contractVariateList"
              type="table"
              data={inputList}
              {...variate}
            />
          </Panel>

          <Panel id="contractAgreement" title="补充条款">
            <Block
              id="contractAgreementList"
              type="table"
              data={list}
              {...contractTmplTableProps}
            />
          </Panel>

          <div>
            {readOnly && (
              <Card title="合同模板附件" id="contractSfs">
                {attachRepoTmpl && (
                  <UploadEL
                    api={`/api/common/contract-tmpls/sfs/token?clsPath=${attachRepoTmpl}&dataKey=${dataKeyTmpl}`}
                    dataKey={dataKeyTmpl}
                    listTypes={'text'}
                    disabled={true}
                  />
                )}
              </Card>
            )}
          </div>

          {mode !== 'create' ? (
            <Panel id="contractAttch" title="合同附件">
              <Block
                id="contractAttchInfo"
                type="other"
                data={formData}
                mode={mode}
              >
                {formData.id && (
                  <UploadEL
                    api={`/api/contract-mgmt/sfs/token?clsPath=${
                      formData.attachRepo
                    }&dataKey=${formData.id}`}
                    dataKey={formData.id}
                    listTypes={'text'}
                  />
                )}
              </Block>
            </Panel>
          ) : (
            <Panel id="contractAttch" title="合同附件">
              <Block
                id="contractAttchInfo"
                type="other"
                data={formData}
                mode={mode}
              >
                {
                  <UploadEL
                    api={`/api/contract-mgmt/sfs/token?clsPath=${attachRepo}`}
                    dataKey={formData.id}
                    listTypes={'text'}
                  />
                }
              </Block>
            </Panel>
          )}
          {mode === 'view' || 'update' ? (
            <CollapseEL>
              <Card
                id="basic"
                title={
                  <div>
                    <span>盖章合同</span>
                    <span style={{ fontSize: 12 }}>
                      （ * 附件名称须前端包含合同名称，例：如合同名称为“根茎类蔬菜采购合同”，附件名称则为“根茎类蔬菜采购合同-XXXXXX” ）
                    </span>
                  </div>
                }
              >
                <UploadEL
                  beforeUpload={handleBeforeUploadFile}
                  api={`/api/contract-mgmt/sfs/token?clsPath=${stampAttachRepo}&dataKey=${
                    formData.id
                  }`}
                  dataKey={formData.id}
                  listTypes={'text'}
                  disabled={!(sealUploadFlag && stampAttachRepo && formData.id)}
                />
              </Card>
            </CollapseEL>
          ) : (
            <></>
          )}
        </Page>
      </div>
    );
  } else {
    return (
      <Loader
        fullScreen={false}
        spinning={loading.effects[`${domain}/query`]}
      />
    );
  }
};

export default connect(({ contractDetail, loading }) => ({
  contractDetail,
  loading
}))(Detail);
