import React from 'react';
import { connect } from 'dva';
import { message } from 'antd';
import { Loader, UploadEL } from '@components';
import { Block, Page, Panel, Toolbar } from '@bizComponents';
import { formUtils, enums } from '@utils';
import Schema from 'async-validator';
import localCfg from './localCfg';
import { routerRedux } from 'dva/router';
import RecpModal from './recpModal';
const { compsMode } = enums;

const ClaimOrderDetail = ({ claimOrderDetail, dispatch, loading }) => {
  const { mode, formData, remoteCfg, recpModalVisible } = claimOrderDetail;
  const { id, items, attachRepo } = formData;
  const dataKey = id ? id : '';
  const domain = 'claimOrderDetail';
  const domainCN = '索赔单详情';

  const remoteValidate = (panelId, blockId) => {
    const rules = localCfg(formData, mode, dispatch, loading)[blockId];
    const panel = remoteCfg.panels.find((i) => i.panelId === panelId);
    const block = panel.blocks.find((i) => i.blockId === blockId);

    block.fields.forEach((f) => {
      const hit = rules.find((lf) => lf.dataIndex === f.fieldId);
      if (hit && f.required) {
        if (hit.options) {
          if (hit.options.rules) {
            const rule = hit.options.rules.find((i) => i.type && i.type !== 'string');
            if (rule) {
              hit.options = {
                ...hit.options,
                rules: [...hit.options.rules, { type: rule.type, required: true, message: '必填' }],
              };
            } else {
              hit.options = {
                ...hit.options,
                rules: [...hit.options.rules, { required: true, message: '必填' }],
              };
            }
          } else {
            hit.options = {
              ...hit.options,
              rules: [{ required: true, message: '必填' }],
            };
          }
        } else {
          hit.options = { rules: [{ required: true, message: '必填' }] };
        }
      }
    });
    return rules;
  };

  const validateTable = (items: object[], formData: object[], cb, handleErrors) => {
    let rulesField = {};
    for (const value of items) {
      if (value.options && value.options.rules) {
        rulesField[value.dataIndex] = value.options.rules;
      }
    }
    const rulesRecord = { type: 'object', fields: rulesField };

    const fields = {};
    const len = formData.length;
    for (let i = 0; i < len; i++) {
      fields[i] = rulesRecord;
    }
    const descriptor = { type: 'array', len, fields };

    const validator = new Schema({ validate: descriptor });
    validator.validate({ validate: formData }, (errors, fields) => {
      if (errors) {

        const args = errors[0].field.split('.');
        const columnError = args[args.length - 1];
        return handleErrors ?
          handleErrors(errors, fields) :
          message.error(`${items.filter((t) => t.dataIndex === columnError)[0].title} ${errors[0].message}`);
      }
      cb();
    });
  };

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

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

  const handleSave = (submitted, type = '') => {
    // 01.Form表单校验
    formUtils.validateForm(
      [...remoteValidate('basic', 'basicInfo')],
      formData, () => {
        if (formData.compsMode === compsMode.COMPS_MODE_ITEM) {
          if (items && items.length > 0) {
            // 02.Table表单校验
            validateTable(
              [...remoteValidate('material', 'materialInfo')],
              items,
              () => {
                // 03.保存操作
                dispatch({ type: `${domain}/save`, payload: { type, submitted: submitted === true } });
              },
              null);
          } else {
            message.error(`物料索赔明细 必填`);
          }
        } else {
          // 03.保存操作
          dispatch({ type: `${domain}/save`, payload: { type, submitted: submitted === true } });
        }
      });
  };

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

  const recpCheck = () => {
    const checkStatus = ['04', '05', '09'];//04:供应商已确认，05:索赔已入库，09:索赔完成
    const { docStatus } = formData;
    return !checkStatus.includes(docStatus);
  }

  const tableProps = {
    rowKey: 'id',
    scroll: { x: '100%' },
    domain,
    dispatch,
    loading,
    dataSource: items,
    showAdd: true,
    showDelete: true,
    showCopy: false,
    size: 'small',
  };

  const modalProps = {
    record: formData,
    visible: recpModalVisible,
    onCancel: hideRecpModal,
  };

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

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

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

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

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

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

    const buttons = [{
      id: 'advice',
      placeholder: '审批意见',
      hidden: mode !== 'approve',
      onChange: (e) => {
        handleAdviceChange(e.target.value);
      },
    }, {
      id: 'edView',
      text: '查看8D报告',
      type: 'primary',
      hidden: !formData.docId8D,
      onClick: () => {
        dispatch(routerRedux.push(`/quality/edo/${formData.docId8D}?mode=view`));
      }
    }, {
      id: 'recpCheck',
      text: '查看入库单',
      type: 'primary',
      hidden: recpCheck(),
      onClick: () => {
        dispatch({ type: `${domain}/showRecpModal` });
      }
    },
    ...remoteCfg.buttons,
    ];

    return (
      <div>
        <Toolbar prcId={formData.prcId} defId={formData.defId} loading={loading} record={formData} mode={mode} buttons={buttons}
          // handleSync={() => {
          //   console.log('press sync');
          // }} handleMail={() => {
          //   console.log('press mail');
          // }} handlePrint={() => {
          //   console.log('press print');
          // }}
          handleCancel={() => { dispatch({ type: `${domain}/cancel` }); }}
        />
        <Page dispatch={dispatch} loading={loading} localCfg={localCfg} remoteCfg={remoteCfg} id="contractDetails" >
          <Panel id="basic" title="基础信息">
            <Block id="basicInfo" type="form" data={formData} mode={mode} onFieldsChange={handleFormChange} />
          </Panel>

          <Panel id="material" title="索赔单明细列表" hidden={formData.compsMode !== compsMode.COMPS_MODE_ITEM}>
            <Block id="materialInfo"
                   type="table"
                   data={items}
                   mode={mode}
                   extraInfo={{suppId : formData.suppId ? formData.suppId : null}}
                   {...tableProps} />
          </Panel>


          {mode !== 'create' ?
            <Panel id="upload" title="索赔公函附件">
              <Block id="uploadInfo" type="other" data={formData} mode={mode} >
                {formData.id && <UploadEL
                  api={`/api/cooperate/quality/sfs/token?clsPath=${attachRepo}&dataKey=${dataKey}`}
                  dataKey={dataKey}
                  listTypes={'text'} />}
              </Block>
            </Panel> :
            <Panel id="upload" title="索赔公函附件">
              <Block id="uploadInfo" type="other" data={formData} mode={mode} >
                {<UploadEL
                  api={`/api/cooperate/quality/sfs/token?clsPath=${attachRepo}&dataKey=${dataKey}`}
                  dataKey={dataKey}
                  listTypes={'text'} />}
              </Block>
            </Panel>
          }

        </Page>
        <RecpModal {...modalProps} />
      </div>);
  } else {
    return <Loader fullScreen={false} spinning={loading.effects[`${domain}/querySingle`]} />;
  }
};

export default connect(({ claimOrderDetail, loading }) => ({ claimOrderDetail, loading }))(ClaimOrderDetail);
