import React from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import { Card, DatePicker, Input, message, Modal, InputNumber } from 'antd';
import { EditableDataTable, FormEL, UdcSelect, UploadEL, SuggestSelect } from '../../../components';
import { formUtils } from '../../../utils';
import { Toolbar } from '../../components';
import { numberUtils } from '@utils';
import Schema from 'async-validator';
const TextArea = Input.TextArea;
const Detail = ({ user, bidDetails, dispatch, loading }) => {
  const { mode, list, currentItem, formData,attachRepo, modalVisible, suppFlag, saveBtnFlag } = bidDetails;
  const domain = 'bidDetails';
  const domainCN = '投标标单详情';
  let readOnly = true;
  if(suppFlag){
    if (mode === 'view') {
      readOnly = true;
    } else if (mode === 'create') {
      readOnly = false;
    } else if (mode === 'update') {
      readOnly = false;
    } else {

    }
  }else{
    readOnly = true;
  }

  const validateItem = () => {
    let itemDescriptor;
    if (suppFlag) {
      itemDescriptor = {
        itemId: { type: 'number', required: true, message: '物料：必选' },
        maxProvideNum: { type: 'number', required: true, message: '最大供货量：必填' },
        taxRate: { required: true, message: '税率：必填' },
        price: { type: 'number', required: true, message: '含税单价(元)：必填' },
        netPrice: { required: true, message: '未税单价(元)：必填' },
        netAmt: { required: true, message: '未税总价(元)：必填' },
        amt: { required: true, message: '含税总价(元)：必填' },
        taxAmt: { required: true, message: '税额(元)：必填' },
      };
      const itemValidator = new Schema(itemDescriptor);
      if (list.length > 0) {
        let num = 0;
        for (const item of list) {
          // console.log('item==>',item)
          itemValidator.validate(item, (errors, fields) => {
            if (errors) {
              num += 1;
              message.error(`${errors[0].message}`);
              return false;
            }
          });
          if (num !== 0) {
            return false;
          }
        }
        if (num === 0) {
          return true;
        } else {
          return false;
        }
      } else {
        message.error('未找到物料');
        return false;
      }
    }
  };
  const handleSave = (submitted) => {
    if (suppFlag) {// 供应商，不会发起流程，只填写选择物料后半部分和报价说明
      formUtils.validateForm(
        [...basic],
        formData, () => {
          if (validateItem()) {
            dispatch({
              type: `${domain}/save`, payload: {
                submitted: submitted,
              },
            });
          }
        }, null);
    } else {
      //todo 提醒一下
      console.log('应该不会出现')
    }
  };
  //基本信息form
  const basic = [
    {
      title: '招标编号',
      dataIndex: 'biNo',
    }, {
      title: '招标名称',
      dataIndex: 'biName',
    }, {
      title: '投标单状态',
      dataIndex: 'docStatus',
      tag: <UdcSelect domain="SRM" code="BID_INFO_STATUS" disabled={true}/>,
    }, {
      title: '投标人',
      dataIndex: 'bidUser',
      options: {
        rules: [
          {
            required: true,
            message: '必填',
          },
        ],
      },
      tag: <Input disabled={readOnly}/>,
    }, {
      title: '投标人电话',
      dataIndex: 'tel',
      options: {
        rules: [
          {
            required: true,
            message: '必填',
          },
        ],
      },
      tag: <Input disabled={readOnly}/>,
    }, {
      title: '投标时间',
      dataIndex: 'docTime',
      tag: <DatePicker format="YYYY-MM-DD HH:mm:ss" style={{ width: '100%' }} disabled={true}/>,
    }, {
      title: '投标次数',
      dataIndex: 'bidNo',
      tag: <Input disabled={true}/>,
    }, {
      title: '投标结果',
      dataIndex: 'bidResult',
      tag: <UdcSelect domain="SRM" code="BID_RESULT" disabled={true}/>,
    }, {
      title: '',
      dataIndex: 'xyz',
    },
    {
      title: '投标说明',
      dataIndex: 'memo',
      // formItemLayout:,
      options: {
        rules: [
          {
            required: true,
            message: '必填',
          },
        ],
      },
      tag: <TextArea autosize={{ minRows: 3, maxRows: 3 }} maxLength={500}/>,
    }];

  //物料列
  const tableProps = {
    rowKey: 'bidInvitingDId',
    scroll: {
      x: 2000,
      y: 500,
    },
    domain: domain,
    dispatch,
    loading,
    dataSource: list,
    showAdd: false,
    showDelete: false,
    showCopy: false,
    size: 'small',
    rowSelection: null,
    footer: null,
    columns: [{
      title: '物料编号',
      dataIndex: 'itemCode',
      className: 'noWrap',
      width: 120,
    }, {
      title: '物料名称',
      dataIndex: 'itemDesc',
      className: 'alignLeft',
      width: 120,
    }, {
      title: '物料规格',
      dataIndex: 'itemSpec',
      className: 'alignLeft',
      width: 120,
    }, {
      title: '单位',
      dataIndex: 'itemUomName',
      className: 'noWrap',
      width: 120,
    }, {
      title: '数量',
      dataIndex: 'itemQty',
      width: 120,
      render: (value, row, index) => {
        return (
          <InputNumber
            disabled={true}
            min={0}
            max={999999999999}
            precision={2}
            step={0.01}
            size="small"
            value={value}
          />
        );
      },
    }, {
      title: '最大供货量',
      dataIndex: 'maxProvideNum',
      width: 120,
      render: (value, row, index) => {
        return (
          <InputNumber
            disabled={readOnly}
            min={0}
            max={row.itemQty}
            precision={2}
            step={0.01}
            size="small"
            value={value}
            onChange={(e) => {  handleChange('maxProvideNum', index, e); }}
          />
          );
      },
    }, {
      title: '税率(%)',
      dataIndex: 'taxRate',
      width: 120,
      render: (value, row, index) => {
        return (
          // <InputNumber
          //   disabled={readOnly}
          //   min={0}
          //   max={999999999999}
          //   precision={2}
          //   step={0.01}
          //   size="small"
          //   value={value}
          //   onChange={(e) => {  handleChange('taxRate', index, e); }}
          // />
          <SuggestSelect
            size="small"
            value={value}
            apiName="tax"
            disabled={readOnly}
            onChange={(e) => {  handleChange('taxRate', index, e); }}
          />
        );
      },
    }, {
      title: '含税单价(元)',
      dataIndex: 'price',
      width: 120,
      formatter: numberUtils.round_half_up_format,
      precision: 4,
      render: (value, row, index) => {
        return (
          <InputNumber
            disabled={readOnly}
            min={0}
            max={999999999999}
            precision={4}
            step={0.0001}
            size="small"
            value={value}
            formatter={(value) => {
              var parts = value.toString().split(".");
              parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
              return parts.join(".");
            }}
            parser={(value) => value.replace(/(,*)/g, '')}
            onChange={(e) => {  handleChange('price', index, e); }}
          />
        );
      },
    }, {
      title: '未税单价(元)',
      dataIndex: 'netPrice',
      width: 120,
      formatter: numberUtils.round_half_up_format,
      precision: 4,
      render: (value, row, index) => {
        return (
          <InputNumber
            disabled={true}
            min={0}
            max={999999999999}
            precision={4}
            step={0.0001}
            size="small"
            value={value}
            formatter={(value) => {
              var parts = value.toString().split(".");
              parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
              return parts.join(".");
            }}
            parser={(value) => value.replace(/(,*)/g, '')}
            onChange={(e) => {  handleChange('netPrice', index, e); }}
          />
          );
      },
    }, {
      title: '含税总价(元)',
      dataIndex: 'amt',
      width: 120,
      formatter: numberUtils.round_half_up_format,
      precision: 4,
      render: (value, row, index) => {
        return (
          <InputNumber
            disabled={true}
            min={0}
            max={999999999999}
            precision={4}
            step={0.0001}
            size="small"
            value={value}
            formatter={(value) => {
              var parts = value.toString().split(".");
              parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
              return parts.join(".");
            }}
            parser={(value) => value.replace(/(,*)/g, '')}
            onChange={(e) => {  handleChange('amt', index, e); }}
          />);
      },
    }, {
      title: '未税总价(元)',
      dataIndex: 'netAmt',
      width: 120,
      formatter: numberUtils.round_half_up_format,
      precision: 4,
      render: (value, row, index) => {
        return (
          <InputNumber
            disabled={true}
          min={0}
          max={999999999999}
          precision={4}
          step={0.0001}
          size="small"
          value={value}
          formatter={(value) => {
            var parts = value.toString().split(".");
            parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            return parts.join(".");
          }}
          parser={(value) => value.replace(/(,*)/g, '')}
          onChange={(e) => {  handleChange('netAmt', index, e); }}
        />);
      },
    }, {
      title: '税额(元)',
      dataIndex: 'taxAmt',
      width: 120,
      formatter: numberUtils.round_half_up_format,
      precision: 2,
      render: (value, row, index) => {
        return (
          <InputNumber
          disabled={true}
          min={0}
          max={999999999999}
          precision={2}
          step={0.01}
          size="small"
          value={value}
          formatter={(value) => {
            var parts = value.toString().split(".");
            parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            return parts.join(".");
          }}
          parser={(value) => value.replace(/(,*)/g, '')}
          onChange={(e) => {  handleChange('taxAmt', index, e); }}
        />);
      },
    }, {
      title: '中标比例(%)',
      dataIndex: 'bidPercent',
      width: 120,
      className: 'noWrap',
      render: (value) => {
        return (
          numberUtils.round_half_up_format(value,0)
        );
      },
    }, {
      title: '中标数量',
      dataIndex: 'bidItemOty',
      width: 120,
      className: 'noWrap',
      render: (value) => {
        return (
          numberUtils.round_half_up_format(value,2)
        );
      },
    }, {
      title: '中标总金额',
      dataIndex: 'bitAmt',
      width: 120,
      className: 'noWrap',
      render: (value) => {
        return (
          numberUtils.round_half_up_format(value,2)
        );
      },
    }],
  };

  /**
   * @param key      字段名
   * @param index    行号
   * @param newValue 新值
   */
  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') {
      // console.log('21333333333', field[key]);
      if (field[key] !== null) {
        dispatch({
          type: `${domain}/updateSpecNo`,
          payload: {
            productCode: field[key],
          },
        });
      } else {
        dispatch({
          type: `${domain}/updateForm`,
          payload: {
            key: 'specNo',
            value: null,
          },
        });
      }
    } else if (key === 'dutyType') {
      dispatch({ type: `${domain}/updateOuId`, payload: { value: field[key] } });
    }

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


  const handleCancel = () => {
    dispatch({ type: `${domain}/cancel` });
  };
  const buttons = [
    {
      id: 'save',
      text: '保存',
      type: 'primary',
      hidden: saveBtnFlag?readOnly:true,
      onClick: () => {
        handleSave(false);
      },
    }, {
      id: 'assign',
      text: '确认投标',
      type: 'primary',
      hidden: saveBtnFlag?readOnly:true,
      onClick: () => {
        handleSave(true);
      },
    }
  ];
  return (
    <div style={{ height: '100%' }}>
      <Toolbar
        buttons={buttons}
        defId={formData.defId}
        handleCancel={handleCancel}
        loading={loading}
        mode={mode}
        prcId={formData.prcId}
        record={{}}
      />

      <Card title="基本信息" id="basic">
        <FormEL items={basic} record={formData} readOnly={readOnly} onFieldsChange={handleFormChange}/>
      </Card>
      {/*投标文件上传=============*/}
      {attachRepo && (( mode === 'create' ?
          <Card id="bidAttch" title="投标文件">
            <UploadEL
              api={`/api/source-mgmt/bid-mgmt/bids/bids/sfs/token?clsPath=${attachRepo}`}
              dataKey={null}
              listTypes={'text'}
            />
          </Card> :
          <Card id="bidAttch" title="投标文件">
            {formData.id &&
            <UploadEL disabled={readOnly}
                      api={`/api/source-mgmt/bid-mgmt/bids/bids/sfs/token?clsPath=${attachRepo}&dataKey=${formData.id}`}
                      dataKey={formData.id}
                      listTypes={'text'}
            />
            }
          </Card>
      ))}
      {/*投标文件上传=============*/}

      <Card title="选择物料" id="material">
        <EditableDataTable {...tableProps} />
      </Card>

    </div>);
};

export default connect(({ bidDetails, loading }) => ({
  bidDetails,
  loading,
}))(Detail);
