import React from 'react';
import { connect } from 'dva';
import { Input, DatePicker, Checkbox, Card, message, Button } from 'antd';
import { EditableDataTable, FormEL, UdcSelect, SuggestSelect } from '@components';
import { Toolbar } from '../../components';
import { formUtils } from '@utils';
import QualifyModal from './QualifyModal';
import moment from 'moment';
import UploadEL from './UploadEL';

const Qualify = ({ dispatch, qualify, loading }) => {
  const { formData, edpPbSupp, addrQualifys, qualifyVisible, qualifyItem } = qualify;
  const domain = 'qualify';

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

  const qualifyProps = {
    dispatch,
    loading,
    domain,
    record: qualifyItem,
    visible: qualifyVisible,
    maskClosable: false,
    width: '80%',
    confirmLoading: loading.effects[`${domain}/update`],
    title: '资质列表',
    wrapClassName: 'vertical-center-modal',
    onCancel() {
      dispatch({
        type: `${domain}/hideQualifyModal`,
      });
    },
  };

  const supp = [{
    title: '供应商编号',
    dataIndex: 'suppCode',
  }, {
    title: '供应商名称',
    dataIndex: 'suppName',
  }, {
    title: '供应商简称',
    dataIndex: 'suppAbbr',
  }, {
    title: '供货区域',
    dataIndex: 'region',
    options: {
      rules: [
        {
          required: true,
          message: '必填',
        }
      ]
    },
    tag: <SuggestSelect apiName="regions" mode="multiple" disabled={true} />,
  }, {
    title: '供应商性质',
    dataIndex: 'gysxz',
    options: {
      rules: [
        {
          required: true,
          message: '必填',
        },
      ],
    },
    tag: <UdcSelect domain="SUPP" code="GYSXZ" disabled={true} mode="multiple" />,
  }, {
    title: '供应商状态',
    dataIndex: 'suppStatus',
    options: {

    },
    tag: <UdcSelect domain="SUPP" code="SUPP_STATUS" disabled={true} />,
  }, {
    title: '审批状态',
    dataIndex: 'approveStatus',
    options: {
    },
    tag: <UdcSelect domain="SUPP" code="SUPP_APPR_STATUS" disabled={true} mode="multiple" />,
  },];

  const qualifyTableProps = {
    rowKey: 'id',
    scroll: { x: '150%' },
    domain: domain,
    dispatch,
    loading,
    dataSource: addrQualifys,
    showAdd: false,
    showDelete: false,
    showCopy: false,
    size: 'small',
    buttons: [{
      key: 'downloadBatch',
      type: 'primary',
      name: '下载所选资质',
      requiredSelected: 2,
      cb: (selectedKeys) => {
        handleDownload(selectedKeys);
      },
    }],
    columns: [{
      title: '证件类型',
      required: true,
      dataIndex: 'qualifyType',
      width: '12%',
      render: (value, row, index) => {
        return (<UdcSelect domain="SUPP"
          code="GYSZZ_TYPE"
          size="small"
          value={value}
          disabled={true}
          onChange={(e) => {
            handleChange('qualifyType', index, e);
          }}
        />);
      },
    }, {
      title: '证件名称',
      required: true,
      dataIndex: 'qualifyName',
      width: '10%',
      // render: (value, row, index) => {
      //   return (<Input
      //     value={value}
      //     size="small"
      //     disabled={true}
      //     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"
      //     disabled={true}
      //     onChange={(e) => {
      //       handleChange('qualifyNo', index, e.target.value);
      //     }}
      //   />);
      // },
    }, {
      title: '证件拥有者',
      required: true,
      dataIndex: 'qualifyOwner',
      width: '8%',
      render: (value, row, index) => {
        return (<UdcSelect domain="SRM"
          code="QUALIFY_OWNER"
          size="small"
          value={value}
          disabled={ true }
          onChange={(e) => {
            handleChange('qualifyOwner', index, e);
          }}
        />);
      },
    }, {
      title: '证件状态',
      dataIndex: 'qualifyStatusDesc',
      width: '6%',
    }, {
      title: '是否长期有效',
      dataIndex: 'longterm',
      width: '6%',
      render: (value, row, index) => {
        return (<Checkbox defaultChecked={value ? true : false} disabled={true}
          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%' }} size="small" disabled={true} value={value ? moment(value) : value}
          disabledDate={disabledDate}
          onChange={(e, data) => {
            handleChange('validFrom', index, data);
          }}
        />);
      },
    }, {
      title: '失效日期',
      dataIndex: 'validTo',
      width: '10%',
      render: (value, row, index) => {
        return (<DatePicker style={{ width: '100%' }} size="small" disabled={true} value={value ? moment(value) : value}
          disabledDate={disabledQualifyDate}
          onChange={(e, data) => {
            handleChange('validTo', index, data);
          }}
        />);
      },
    }, {
      title: '关联物料',
      dataIndex: 'itemName',
      width: '10%',
    }, {
      title: '附件',
      dataIndex: 'attachRepo',
      width: '16%',
      render: (value, row, index) => {
        let clsPath = row.attachRepo ? row.attachRepo : Math.abs(row.id);
        let dataKey = row.id > 0 ? row.id : '';
        return (
          <UploadEL
            currentData={ row }
            size={'small'}
            api={`/api/supp/sfs/token?clsPath=${clsPath}&dataKey=${dataKey}`}
            dataKey={`${dataKey}`}
            listTypes={['text', 'picture', 'picture-card']}
            disabled={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, attachChangeFlag :true , file: [file] }
  //     });
  //     return false;
  //   };
  //   const onRemove = () => {
  //     dispatch({
  //       type: `${domain}/deleteUploadState`,
  //       payload: { index, file: [] }
  //     });
  //   };
  //   const onDownload = () => {
  //     upload.onDownload(record.attachRepo, fileName);
  //   };
  //   const disabled = false;
  //   return upload.render(fileName, beforeUpload, onRemove, onDownload ,disabled);
  // };

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

  const handleFormChange = (field) => {
    const key = Object.keys(field)[0];

    if (key === 'productCode') {

      if (field[key] !== null) {
        dispatch({
          type: `${domain}/updateSpecNo`,
          payload: {
            productCode: field[key],
          },
        });
      } else {
        dispatch({
          type: `${domain}/updateForm`,
          payload: {
            key: 'specNo',
            value: null,
          },
        });
      }

      const old = formData.productCode;

      if (old !== field[key]) {
        dispatch({ type: `${domain}/updateFaultModeCode`, payload: { value: old } });
      }
    } else if (key === 'dutyType') {
      dispatch({ type: `${domain}/updateOuId`, payload: { value: field[key] } });
    }

    dispatch({
      type: `${domain}/updateForm`,
      payload: {
        key,
        value: field[key],
      },
    });
  };

  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['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;
      }
    }

    dispatch({ type: `${domain}/qualify` });
  };

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

  const handleQualifyModal = () => {
    dispatch({
      type: `${domain}/qualifyModal`,
      payload: {
        id: edpPbSupp.id,
      },
    });
  };

  const handleDownload = (selectedKeys) => {
    const selectedData = addrQualifys.filter(i => selectedKeys.includes(i.id));
    if(selectedData && selectedData.length > 0) {
      const downloadData = new Array();
      selectedData.forEach(item => {
        downloadData.push({
          clsPath: item.attachRepo,
          dataKey: item.id
        });
      });
      dispatch({
        type: `${domain}/download`,
        payload: {
          downloadData
        }
      });
    }
  };

  return (
    <div>
      {(formData.authField !== 'EP') &&
        <Toolbar domain={domain} loading={loading}
          buttons={[]}
          handleCancel={handleCancel}
        />
      }
      {(formData.authField === 'EP') &&
        <Toolbar domain={domain} loading={loading}
          buttons={[{
            id: 'save',
            text: '提交',
            type: 'primary',
            onClick: handleSave,
          },]}
          handleCancel={handleCancel}
        />
      }

      <Card title="基础信息" loading={loading.effects[`${domain}/query`]} id="suppBase">
        <FormEL items={supp} record={edpPbSupp} onFieldsChange={handleFormChange} />
      </Card>
      <Card title={<div>资质证照 <Button key="save" type="primary" onClick={handleQualifyModal}>查看所有资质</Button></div>}
        loading={loading.effects[`${domain}/query`]} id="suppQualify">
        <EditableDataTable {...qualifyTableProps} />
        {qualifyVisible && <QualifyModal {...qualifyProps} />}
      </Card>
    </div>
  );
};

export default connect(({ qualify, loading }) => ({ qualify, loading }))(Qualify);
