import React from 'react';
import { connect } from 'dva';
import { Icon, message } from 'antd';
import localCfg from './localCfg';
import { Loader, UploadEL } from '@components';
import { Block, Page, Panel, Toolbar } from '@bizComponents';
import { formUtils } from '@utils';
import Schema from 'async-validator';
import styles from './index.less';

const PerformanceDetail = ({ performanceDetail, dispatch, loading }) => {
  const { formData, scores, mode, remoteCfg, showSubmit } = performanceDetail;
  const { score, finalScore, sgName, showScore } = formData;
  const { scoreQuality, scoreDelivery, scoreService, scoreAddition } = scores;

  const domain = 'performanceDetail';
  const domainCN = '供应商绩效考核评估';

  const formItemLayout = {
    colon: false,
    labelCol: {
      span: 4,
    },
    wrapperCol: {
      span: 14,
    },
    style: {},
  };
  const colProps = {
    xs: 12,
    sm: 12,
    md: 12,
    xl: 12,
  };
  const adjustProps = {
    xs: 24,
    sm: 24,
    md: 24,
    xl: 24,
  };

  const tableProps = {
    rowKey: 'id',
    scroll: {
      x: '100%',
      y: 400,
    },
    domain,
    dispatch,
    loading,
    footer: () => {
      return null;
    },
    enableSelection: false,
    style: { marginBottom: 20 },
  };

  // const getDefaultValues = () => {
  //     let init = {};
  //     rectify.forEach((item) => {
  //         if (item.options && item.options.initialValue) {
  //             init[item.dataIndex] = item.options.initialValue;
  //         }
  //     });
  //     return init;
  // };

  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(`${formData[args[1]][items[0]['dataIndex']]}：
          ${items.filter((t) => t.dataIndex === columnError)[0].title}
          ${errors[0].message}`);
      }
      cb();
    });
  };

  const handleSave = (submitted, type = '') => {
    const scoreMerge = [...scoreQuality, ...scoreDelivery, ...scoreService, ...scoreAddition];
    // 01.Form表单校验
    formUtils.validateForm(
      [
        ...localCfg(formData, mode, dispatch, loading).rectifyInfo,
        ...localCfg(formData, mode, dispatch, loading).adjust,
      ],
      formData,
      () => {
        // 02.Table表单校验
        validateTable(
          [...localCfg(formData, mode, dispatch, loading).qualityInfo],
          scoreMerge,
          () => {
            // 03.保存操作
            dispatch({
              type: `${domain}/save`,
              payload: {
                type,
                submitted: submitted === true,
              },
            });
          },
          null
        );
      });
  };

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

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

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

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

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

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

    const buttons = [{
      id: 'submit',
      text: '提交',
      type: 'primary',
      hidden: !showSubmit && mode !== 'create',
      onClick: () => {
        handleSave(true);
      },
    }, {
      id: 'advice',
      placeholder: '审批意见',
      hidden: mode !== 'approve',
      onChange: (e) => {
        handleAdviceChange(e.target.value);
      },
    },
    ...remoteCfg.buttons,
    ];

    function getHelp() {
      window.open('/static/help/供应商履约考核制度-20180410.doc', '_blank');
    }

    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="performanceDetail">
          <Panel
            title={
              <div className={styles.baseHead}>
                <span>基本信息</span>
                <span className={styles.baseHelp}>
                  <a href="javascript:;" onClick={ getHelp }><Icon type="download"/> 下载绩效评分制度</a>
                </span>
              </div>
            }
            id="basic">
            <Block id="basicInfo" type="form" data={formData} readOnly={true} />
          </Panel>

          <Panel id="rectify" title="整改信息">
            <Block id="rectifyInfo" type="form" data={formData} mode={mode} formItemLayout={formItemLayout}
              ColProps={colProps} onFieldsChange={handleFormChange} />
          </Panel>

          <Panel id="scoring"
            title={'绩效考核评估：' + sgName + ' 类 ' + showScore + ' 分' + (finalScore ? ('( 原评分：' + score + ' )') : '')}>
            <Block id="adjust" type="form" data={formData} mode={mode} ColProps={adjustProps}
              onFieldsChange={handleFormChange} />
            <Block id="qualityInfo" type="table" data={scoreQuality} mode={mode} {...tableProps} />
            <Block id="deliveryInfo" type="table" data={scoreDelivery} mode={mode} {...tableProps} />
            <Block id="serviceInfo" type="table" data={scoreService} mode={mode} {...tableProps} />
            <Block id="additionInfo" type="table" data={scoreAddition} mode={mode} {...tableProps} />
          </Panel>

          <Panel id="attachment" title="绩效考核附件">
            <Block id="attachmentInfo" type="other" data={formData} mode={mode}>
              {formData.id && <UploadEL api={'/performance/sfs-client/sfs/token'} dataKey={formData.id} listTypes={'text'}
              />}
            </Block>
          </Panel>
        </Page>
      </div>
    );
  } else {
    return <Loader fullScreen={false} spinning={loading.effects[`${domain}/query`]} />;
  }
};

export default connect(({ performanceDetail, loading }) => ({ performanceDetail, loading }))(PerformanceDetail);
