import React from 'react';
import { connect } from 'dva';
import { Button, Card, DatePicker, message, Checkbox, Input, InputNumber } from 'antd';
import { EditableDataTable, FormEL, UploadEL } from '@components';
import ItemPicker from './ItemPicker';
import { formUtils } from '@utils';
import styles from './index.less';
import UdcSelect from './UdcSelect';
import moment from 'moment';

const Register = ({ dispatch, register, loading }) => {
  const { addrQualifys, srmSuppAdd, edpPbSupp, repo } = register;

  const domain = 'register';
  const { TextArea } = Input;

  const disabledDate = (current) => current && current > moment().endOf('day');
  const disabledQualifyDate = (current) => current && current < moment().endOf('day');

  // let options = []
  // statusList.length && statusList.map((status, index) => options.push(
  //  <Option key={status.code}>{status.name}</Option>))
  const produceSelect = [{
    title: '质量检验',
    dataIndex: 'zljy',
    options: {
      initialValue: [],
    },
    tag: <UdcSelect domain="SUPP" code="ZLJY" mode="multiple" />,
  }, {
    title: '认证体系',
    dataIndex: 'rztx',
    options: {
      initialValue: [],
    },
    tag: <UdcSelect domain="SUPP" code="RZTX" mode="multiple" />,
  }, {
    title: '质量控制点报表',
    dataIndex: 'zlkzdbb',
    options: {
      initialValue: [],
    },
    tag: <UdcSelect domain="SUPP" code="ZLKZDBB" mode="multiple" />,
  }, {
    title: '检验范围',
    dataIndex: 'jyfw',
    options: {
      initialValue: [],
    },
    tag: <UdcSelect domain="SUPP" code="JYFW" mode="multiple" />,
  }, {
    title: '产品执行标准',
    dataIndex: 'cpzxbz',
    options: {
      initialValue: [],
    },
    tag: <UdcSelect domain="SUPP" code="CPZXBZ" mode="multiple" />,
  }, {
    title: '供货质量记录',
    dataIndex: 'ghzljl',
    options: {
      initialValue: [],
    },
    tag: <UdcSelect domain="SUPP" code="GHZLJL" mode="multiple" />,
  },];


  const produce = [{
    title: '工厂员工人数',
    dataIndex: 'gcygrs',
    tag: <InputNumber style={{ width: '100%' }} min={0} />,
  }, {
    title: '厂房总面积',
    dataIndex: 'cfzmj',
    options: {
      rules: [
        {
          max: 40,
          message: '请输入不超过40个字符',
        },
      ],
    },
    tag: <Input addonAfter="㎡" />,
  }, {
    title: '原料仓储面积',
    dataIndex: 'ylccmj',
    options: {
      rules: [
        {
          max: 40,
          message: '请输入不超过40个字符',
        },
      ],
    },
    tag: <Input addonAfter="㎡" />,
  }, {
    title: '开发技术人数',
    dataIndex: 'kfjsrs',
    tag: <InputNumber style={{ width: '100%' }} min={0} />,
  }, {
    title: '生产面积',
    dataIndex: 'scmj',
    options: {
      rules: [
        {
          max: 40,
          message: '请输入不超过40个字符',
        },
      ],
    },
    tag: <Input addonAfter="㎡" />,
  }, {
    title: '冷冻冷藏库面积',
    dataIndex: 'ldlckmj',
    options: {
      rules: [
        {
          max: 40,
          message: '请输入不超过40个字符',
        },
      ],
    },
    tag: <Input addonAfter="㎡" />,
  }, {
    title: '品质检验人数',
    dataIndex: 'pzjyrs',
    tag: <InputNumber style={{ width: '100%' }} min={0} />,
  }, {
    title: '生产线',
    dataIndex: 'scx',
    options: {
      rules: [
        {
          max: 40,
          message: '请输入不超过40个字符',
        },
      ],
    },
    tag: <Input />,
  }, {
    title: '成品库面积',
    dataIndex: 'cpkmj',
    options: {
      rules: [
        {
          max: 40,
          message: '请输入不超过40个字符',
        },
      ],
    },
    tag: <Input addonAfter="㎡" />,
  }, {
    title: '主要生产设备',
    dataIndex: 'zyscsb',
    options: {
      initialValue: '',
    },
    tag: <TextArea autosize={{ minRows: 2, maxRows: 6 }} />,
  }, {
    title: '供应商来源',
    dataIndex: 'gysly',
    options: {
      initialValue: '',
    },
    tag: <TextArea autosize={{ minRows: 2, maxRows: 6 }} />,
  }];

  const qualifyTableProps = {
    rowKey: 'id',
    scroll: { x: '125%' },
    domain: domain,
    dispatch,
    loading,
    dataSource: addrQualifys,
    showAdd: true,
    showDelete: true,
    showCopy: false,
    size: 'small',
    enableSelection: true,
    columns: [{
      title: '证件类型',
      required: true,
      dataIndex: 'qualifyType',
      width: '15%',
      render: (value, row, index) => {
        return (<UdcSelect domain="REG"
          code="GYSZZ_TYPE"
          value={value}
          size="small"
          onChange={(e) => {
            handleChange('qualifyType', index, e);
          }}
        />);
      },
    }, {
      title: '证件名称',
      required: true,
      dataIndex: 'qualifyName',
      width: '15%',
      render: (value, row, index) => {
        return (<Input
          value={value}
          size="small"
          style={{ textAlign: 'left' }}
          onChange={(e) => {
            handleChange('qualifyName', index, e.target.value);
          }}
        />);
      },
    }, {
      title: '证件编号',
      required: true,
      dataIndex: 'qualifyNo',
      width: '10%',
      render: (value, row, index) => {
        return (<Input
          value={value}
          size="small"
          onChange={(e) => {
            handleChange('qualifyNo', index, e.target.value);
          }}
        />);
      },
    }, {
      title: '证件拥有者',
      required: true,
      dataIndex: 'qualifyOwner',
      width: '10%',
      render: (value, row, index) => {
        return <UdcSelect
          domain="SRM"
          code="QUALIFY_OWNER"
          size="small"
          value={ value }
          onChange={(e) => {
            handleChange('qualifyOwner', index, e);
          }}
        /> },
    }, {
      title: '是否长期有效',
      dataIndex: 'longterm',
      width: '8%',
      render: (value, row, index) => {
        return (<Checkbox defaultChecked={value ? true : false}
          onChange={(e) => {
            if (e.target.checked) {
              handleChange('longterm', index, 1);
              handleChange('validTo', index, null);
            } else {
              handleChange('longterm', index, 0);
            }
          }} />);
      },
    }, {
      title: '生效日期',
      dataIndex: 'validFrom',
      width: '10%',
      render: (value, row, index) => {
        return (<DatePicker style={{ width: '100%' }}
          value={value ? moment(value) : value}
          size="small"
          disabledDate={disabledDate}
          onChange={(e, data) => {
            handleChange('validFrom', index, data);
          }}
        />);
      },
    }, {
      title: '失效日期',
      dataIndex: 'validTo',
      width: '10%',
      render: (value, row, index) => {
        return (<DatePicker style={{ width: '100%' }} value={value ? moment(value) : value}
          size="small"
          disabled={row.longterm ? true : false}
          disabledDate={disabledQualifyDate}
          onChange={(e, data) => {
            handleChange('validTo', index, data);
          }}
        />);
      },
    }, {
      title: '关联物料',
      dataIndex: 'relateItem',
      width: '10%',
      render: (value, row, index) => <ItemPicker
        apiName='regItems'
        value={{ id: row.relateToItemId, code: row.itemCode, name: row.itemName }}
        onChange={(data) => {
          handleChange('relateItem', index, data);
        }}
      />,
    }, {
      title: '附件',
      dataIndex: 'attachRepo',
      width: '12%',
      render: (value, row, index) => {
        let clsPath = Math.abs(row.id);
        return (<UploadEL size={'small'} api={`/register/sfs/token?clsPath=${clsPath}`} dataKey={''} listTypes={['text', 'picture', 'picture-card']}
          disabled={false} />
        );
      }
    },],
  };

  const handleChange = (key, index, newValue) => {
    dispatch({ type: `${domain}/updateCell`, 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 prev = () => {
    dispatch({
      type: `${domain}/minusCurrent`,
    });
  };

  const next = () => {

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

    let scoreMerge = [...addrQualifys,];

    for (const iterator of scoreMerge) {
      if (iterator['qualifyName'].length > 40) {
        message.error('证件名称 请输入不超过40个字符', 3);
        return 0;
      }
      if (iterator['qualifyNo'].length > 40) {
        message.error('证件编号 请输入不超过40个字符', 3);
        return 0;
      }
      if (!iterator['longterm'] && !iterator['validTo']) {
        message.error('请确认证件长期有效 或输入失效日期', 3);
        return 0;
      }
    }

    formUtils.validateForm([...produceSelect, ...produce], Object.assign(edpPbSupp, srmSuppAdd), () => {
      dispatch({
        type: `${domain}/requireQualifys`,
      });
    });

  };

  return (
    <div>
      <Card title="生产情况" id="produce">
        <FormEL items={produceSelect} record={edpPbSupp} onFieldsChange={handleFormChange} />
        <FormEL items={produce} record={srmSuppAdd} onFieldsChange={handleAddFormChange} />
      </Card>

      <Card title="资质证照" id="feedback">
        <EditableDataTable {...qualifyTableProps} />
      </Card>

      <div className={styles.registerButton}>
        <Button onClick={prev}> 返回 </Button>
        <Button style={{ marginLeft: 8 }} type="primary" onClick={next}>下一步</Button>
      </div>
    </div>
  );
};

export default connect(({ register, loading }) => ({ register, loading }))(Register);
