import React from 'react';
import { connect } from 'dva';
import { Card, Checkbox, DatePicker, Input,InputNumber,message } from 'antd';
import { EditableDataTable, FormEL, UdcSelect ,SuggestSelect} from '../../../components';
import { dataUtils,formUtils } from '../../../utils';
import { Toolbar } from '../../components';
import styles from './index.less';
import moment from 'moment';
import upload from './Upload';
import { Block, Page, Panel, Toolbar } from '@bizComponents';
import localCfg from './localCfg';
import remoteCfg from './remoteCfg';

const SupplierDetail = ({ dispatch, supplierDetail, loading ,}) => {
  const { items, mode,addrContacts,addrQualifys,edpPbSupp,srmSuppAdd, formData } = supplierDetail;
  const { TextArea } = Input;

  const domain = 'supplierDetail';
  const CheckboxGroup = Checkbox.Group;
  let viewFlag = true;
  let readOnly = false;

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

  const introduction = [{
    dataIndex: 'remark',
    options: {

    },
    colProps: {
      xs: 24,
      sm: 24,
      md: 24,
      xl: 24,
      lg: 24,
      style: {},
    },
    formItemLayout: {
      labelCol: {
        span: 0,
      },
      wrapperCol: {
        span: 24,
      },
    },
    tag: <TextArea disabled={readOnly} rows={10} />,
  }];

  const addrTable = {
    rowKey: 'id',
    scroll: {
      x: '100%',
      y: 400,
    },
    domain: domain,
    dispatch,
    loading,
    showAdd: false,
    showDelete: false,
    showCopy: false,
    size: 'small',
    enableSelection: true,
    buttons: [{
      key: 'addAddrRow',
      type: 'primary',
      name: '新增',
      hidden:!viewFlag,
      requiredSelected: 0,
      cb: (selectedRowKeysa,) => {
        let newData = {};
        newData.id = dataUtils.getRandomInt(-99999999, -1);
        dispatch({
          type: `${domain}/addAddrRow`,
          payload: { ...newData },
        });
      },
    }, {
      key: 'deleteAddrRow',
      type: 'primary',
      name: '删除',
      hidden:!viewFlag,
      requiredSelected: 2,
      cb: (selectedRowKeys) => {
        selectedRowKeys.forEach(id => {
          dispatch({
            type: `${domain}/deleteAddrRow`,
            payload: id,
          });
        });
      },
    }],
  };

  const qualifyTable = {
    rowKey: 'id',
    scroll: {
      x: '130%',
      y: 400,
    },
    domain,
    dispatch,
    loading,
    showAdd: viewFlag,
    showDelete: viewFlag,
    showCopy: false,
    size: 'small',
    enableSelection: true,
  };

  const renderUploadColumns = (record, index, column) => {
    const uploadedFiles = Object.assign([], record.viewFiles);
    const fileName = (uploadedFiles.length > 0) ? (
        uploadedFiles[0].fileName ?
        uploadedFiles[0].fileName : uploadedFiles[0].name) : '';

    const beforeUpload = (file) => {
      dispatch({
        type: `${domain}/updateUploadState`,
        payload: {  index, file: [file] }
      });
      return false;
    };

    const onRemove = () => {
      dispatch({
        type: `${domain}/updateUploadState`,
        payload: { index, file: [] }
      });
    };
    return upload.render(fileName, beforeUpload, onRemove);
  };

  const handleChange = (key, index, newValue) => {
    dispatch({ type: `${domain}/updateCell`, payload: { key, index, value: newValue } });
  };

  const handleAddrChange = (key, index, newValue) => {
    dispatch({ type: `${domain}/updateAddrCell`, payload: { key, index, value: newValue } });
  };


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

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

  const getDefaultValues = () => {
    let init = {

    };
    supp.forEach((suppItem) => {
      if (suppItem.options && suppItem.options.initialValue) {
        init[suppItem.dataIndex] = suppItem.options.initialValue;
      }
    });
    produce.forEach((produceItem) => {
      if (produceItem.options && produceItem.options.initialValue) {
        init[produceItem.dataIndex] = produceItem.options.initialValue;
      }
    });
    produceSelect.forEach((produceSelectItem) => {
      if (produceSelectItem.options && produceSelectItem.options.initialValue) {
        init[produceSelectItem.dataIndex] = produceSelectItem.options.initialValue;
      }
    });

    return init;
  };

  const handleSave = () => {

    if (addrQualifys.length && formUtils.checkEmptyField(addrQualifys, qualifyTableProps.columns) === true) {
      message.error('请输入证件信息的必填项', 3);
      return 0;
    }

    let scoreMerge = [...addrQualifys, ];

    for (const iterator of scoreMerge) {
      if(iterator['viewFiles'] && iterator['viewFiles'].length > 0){
        upload.onUpload(iterator['attachRepo'], iterator['viewFiles']);
      }
    }

    if (addrContacts.length && formUtils.checkEmptyField(addrContacts, addrTableProps.columns) === true) {
      message.error('请输入联系信息的必填项', 3);
      return 0;
    }

    if (!edpPbSupp.gysylsx || edpPbSupp.gysylsx.length === 0) {
      message.error('请至少选择一项物料', 3);
      return 0;
    }

    if (!readOnly) {
      formUtils.validateForm([...supp,...produce,...produceSelect,], Object.assign(getDefaultValues(), edpPbSupp,srmSuppAdd), () => {
        dispatch({ type: `${domain}/save`});
      });
    } else {
      formUtils.validateForm([...supp,], edpPbSupp, () => {
        dispatch({ type: `${domain}/save` });
      });
    }
  };

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

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

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

  function onChange(checkedValues) {
    const key='gysylsx';
    dispatch({
      type: `${domain}/updateForm`,
      payload: {
        key,
        value: checkedValues,
      },
    });
  }


  let suppItem = [];
  items.length && items.map((status, index) => {
    suppItem.push(
      {
        label: status.name,
        value: status.code,
      });
  });


  return (
    <div>
      {(mode === 'view') &&
        <Toolbar domain={domain} loading={loading} formData={formData}
          readOnly={readOnly}
          mode={mode}
          buttons={[]}
          handleCancel={handleCancel}
        />
      }
      {(mode === 'update') &&
        <Toolbar domain={domain} loading={loading} formData={formData}
          readOnly={readOnly}
          mode={mode}
          buttons={[{
            id: 'save',
            text: '提交',
            type: 'primary',
            onClick:handleSave,
          },]}
          handleCancel={handleCancel}
        />
      }
      {(mode === 'approval') &&
        <Toolbar domain={domain} loading={loading} formData={formData}
          readOnly={readOnly}
          mode={mode}
          buttons={[{
            id: 'advice',
            placeholder: '请输入意见',
            onChange: (e) => {
              dispatch({ type: `${domain}/updateState`, payload: { advice: e.target.value } });
            },
          },{
            id: 'assign',
            text: '同意',
            type: 'primary',
            onClick: handleApprove,
          }, {
            id: 'reject',
            text: '拒绝',
            type: 'primary',
            onClick: handleReject,
          }]}
          handleCancel={handleCancel}
        />
      }

      {/*handleDispatch={handleDispatch}*/}
      {/*handleReject={handleReject}*/}
      {/*handleApprove={handleApprove}*/}
      {/*handleCancel={handleCancel}*/}
      {/*handleAdviceChange={handleAdviceChange}*/}

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

        <Panel id="supp" title="基本信息">
          <Block id="suppInfo" type="form" data={edpPbSupp} onFieldsChange={handleFormChange} />
        </Panel>

        <Panel id="addr" title="联系信息">
          <Block id="contactInfo" type="form" data={edpPbSupp} onFieldsChange={handleFormChange} />
          <Block id="addrTableProps" type="table" data={addrContacts} {...addrTable} />
        </Panel>

        <Panel id="produce" title="生产情况">
          <Block id="produceSelectInfo" type="form" data={edpPbSupp} onFieldsChange={handleFormChange} />
          <Block id="produceInfo" type="form" data={srmSuppAdd} onFieldsChange={handleAddFormChange} />
        </Panel>

        <Panel id="qualify" title="资质证照">
          <Block id="qualifyTableProps" type="table" data={addrQualifys} {...qualifyTable} />
        </Panel>

        {/*<Panel id="suppItem" title="物料品类">
          <CheckboxGroup options={suppItem} className={styles.checkbox} value={edpPbSupp.gysylsx} onChange={onChange}  disabled={(mode === 'approval')||(mode === 'view')}/>
        </Panel>*/}

        <Panel id="introduction" title="自我介绍">
          <Block id="introductionInfo" type="form" data={edpPbSupp} onFieldsChange={handleFormChange} />
        </Panel>
      </Page>
    </div>
  );
};

export default connect(({ supplierDetail, loading }) => ({ supplierDetail, loading }))(SupplierDetail);
