import { Card, DatePicker, Input, InputNumber, Steps, TimePicker } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import React from 'react';

import { Toolbar } from '@bizComponents';
import { CollapseEL, EditableDataTable, FormEL, Loader } from '@components';
import { theme } from '@utils';
import { numberUtils } from '@utils';

const { TextArea } = Input;

// 对金额类型字段进行格式化
const formatNum = (value, type) => {
  if (type === 'amt') {
    return (value || value === 0) ? `${parseFloat(value).toFixed(2)}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',') : '';
  } else if (type === 'qty') {
    return (value || value === 0) ? `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',') : '';
  } else {
    return value;
  }
  ;
};

// 设定不可选日期（currentDate之前的）
const disabledStartDate = (current) => {
  return current && current < moment().add(-1, 'days').endOf('day');
};

const Detail = ({ purchasingOrderDetails, dispatch, loading, app }) => {
  const { mode, list, formData, remoteCfg } = purchasingOrderDetails;
  const { promiseDate, deliveryTimeFrom, deliveryTimeTo } = formData;

  // const { user } = app.user;

  // const editable = formData.docStatus === '290' && user.entType === 'supp'
  //   && formData.docType === 'OP' && formData.approveStatus === '00';

  const editable = remoteCfg && !remoteCfg.buttons.find(b => b.id === 'confirm').hidden;
  const flowModuleShow = mode === 'approval' && formData.approveStatus === '01';

  const domain = 'purchasingOrderDetails';
  const domainCN = '采购订单明细';

  let readOnly = false;

  const handleUpdateValue = (index, key, value, maxVal) => {
    dispatch({
      type: `${domain}/checkValid`,
      payload: { index, key, value, maxVal }
    });
  };

  // function disabledRangeTime(_, type) {
    // return {
    //   disabledHours: () => range(0, 60).splice(20, 4),
    //   disabledMinutes: () => range(0, 31),
    // };
  // };

  const handleDateChange = (value, key) => {
    dispatch({
      type: 'purchasingOrderDetails/updatePromisePeriod',
      payload: { value, key }
    });
  };

  //基本信息form
  const basic = [
    {
      title: '采购单编号',
      dataIndex: 'docNo',
    }, {
      title: '采购单类型',
      dataIndex: 'docTypeName',
    }, {
      title: '采购单状态',
      dataIndex: 'docStatusName',
    // }, {
    //   title: '订单系统来源',
    //   dataIndex: 'poSource',
    }, {
      title: '采购员',
      dataIndex: 'poAgentName',
    }, {
      title: '制单人员',
      dataIndex: 'createUserName',
    }, {
      title: '制单日期',
      dataIndex: 'docTime',
    }, {
      title: '结算模式',
      dataIndex: 'paymentTermName',
    // }, {
    //   title: '运输方式',
    //   dataIndex: 'deliveryTypeName',
    // }, {
    //   title: '配送方式',
    //   dataIndex: 'distTypeName',
    }, {
      title: '供应商编号',
      dataIndex: 'suppCode',
    }, {
      title: '供应商名称',
      dataIndex: 'suppName',
    // }, {
    //   title: '发货地址',
    //   dataIndex: 'deliveryAddr',
    }, {
      title: '收货单位',
      dataIndex: 'acceptOuName',
    }, {
      title: '收货地址',
      dataIndex: 'acceptAddr',
    }, {
      title: '总金额(不含税)',
      dataIndex: 'netAmt',
    }, {
      title: '总金额(含税)',
      dataIndex: 'amt',
    }, {
      title: '税额',
      dataIndex: 'taxAmt',
    }, {
      title: '币种',
      dataIndex: 'currName',
    }, {
      title: '要求交货日期',
      dataIndex: 'demandDate',
    }, {
      title: '承诺交货期间',
      dataIndex: 'promisePeriod',
      tag:
        <div>
          <DatePicker
            disabledDate={disabledStartDate}
            value={promiseDate && moment(promiseDate, 'YYYY-MM-DD')}
            style={{ width: '50%' }}
            disabled={!editable}
            onChange={(date, dateString) => handleDateChange(dateString, 'promiseDate')}
          />
          <TimePicker
            value={deliveryTimeFrom && moment(deliveryTimeFrom, 'HH:mm')}
            format={'HH:mm'}
            style={{ width: '25%' }}
            className={'deliveryTimeFrom'}
            disabled={!editable}
            onChange={(time, timeString) => handleDateChange(timeString, 'deliveryTimeFrom')}
          />
          <TimePicker
            value={deliveryTimeTo && moment(deliveryTimeTo, 'HH:mm')}
            format={'HH:mm'}
            style={{ width: '25%' }}
            className={'deliveryTimeTo'}
            disabled={!editable}
            onChange={(time, timeString) => handleDateChange(timeString, 'deliveryTimeTo')}
          />
        </div>,
      colProps: {
        xs: 12,
        sm: 12,
        md: 12,
        xl: 12,
      },
    }, {
      title: '备注',
      dataIndex: 'remark',
      tag: <TextArea disabled autosize={{ minRows: 2, maxRows: 6 }}/>,
      colProps: {
        xs: 20,
        sm: 20,
        md: 20,
        xl: 20,
      },
      formItemLayout: {
        labelCol: { span: 3 },
        wrapperCol: { span: 20 },
      },
    }, {
      title: '供应商反馈',
      dataIndex: 'suppRemark',
      // tag: <Input.TextArea disabled={!remarkReadOnly} autosize={{ minRows: 2, maxRows: 6 }} />,
      tag: <TextArea disabled={!editable} autosize={{ minRows: 2, maxRows: 6 }}/>,
      colProps: {
        xs: 20,
        sm: 20,
        md: 20,
        xl: 20,
      },
      formItemLayout: {
        labelCol: { span: 3 },
        wrapperCol: { span: 20 },
      },
    }];

  //物料列
  const tableProps = {
    rowKey: 'id',
    scroll: {
      x: '150%',
      y: 400,
    },
    domain: domain,
    dispatch,
    loading,
    dataSource: list,
    size: 'small',
    rowSelection: null,
    enableSelection: false,
    footer: null,
    readOnly,
    columns: [{
      title: '物料编号',
      dataIndex: 'itemCode',
      width: '7%',
    }, {
      title: '物料名称',
      dataIndex: 'itemName',
      width: '10%',
    }, {
      title: '规格',
      dataIndex: 'spec',
      width: '6%',
    }, {
      title: '单位',
      dataIndex: 'uom',
      width: '5%',
    }, {
      title: '采购数量',
      dataIndex: 'qty',
      className: 'alignRight',
      width: '6%',
      render: (value, row, index) => {
        return formatNum(value, 'qty');
      }
    }, {
      title: '承诺数量',
      dataIndex: 'promiseQty',
      width: '7%',
      render: (value, row, index) => {
        return (
          <InputNumber
            value={value}
            max={999999999999}
            disabled={row.qty < 0 || !editable}
            formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
            parser={value => value.replace(/\$\s?|(,*)/g, '')}
            onChange={(value) => handleUpdateValue(index, 'promiseQty', value, 999999999999)}
          />
        );
      },
    }, {
      title: '数量差异',
      dataIndex: 'diffQty',
      className: 'alignRight',
      width: '6%',
      render: (value) => {
        return (<span style={{ color: theme.color.deepRed }}>{formatNum(value, 'qty')}</span>);
      }
    }, {
      title: '未税单价',
      dataIndex: 'netPrice',
      width: '7%',
      className: 'alignRight',
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value, 4)
        );
      }
    }, {
      title: '含税单价',
      dataIndex: 'price',
      width: '7%',
      className: 'alignRight',
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value, 4)
        );
      }
    }, {
      title: '未税总价',
      dataIndex: 'netAmt',
      width: '7%',
      className: 'alignRight',
      render: (value, row, index) => {
        return (
          formatNum(value, 'amt')
        );
      }
    }, {
      title: '含税总价',
      dataIndex: 'amt',
      width: '7%',
      className: 'alignRight',
      render: (value, row, index) => {
        return (
          formatNum(value, 'amt')
        );
      }
    }, {
      title: '税率(%)',
      dataIndex: 'taxRate',
      width: '5%',
    }, {
      title: '税额',
      dataIndex: 'taxAmt',
      width: '8%',
      className: 'alignRight',
      render: (value, row, index) => {
        return (
          formatNum(value, 'amt')
        );
      }
    }, {
      title: '备注',
      dataIndex: 'remark',
      width: '15%',
    }],
  };

  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,
          },
        });
      }
    } 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 onClickIcon = (value) => {
  //   dispatch({type: 'purchasingOrderDetails/showTitle', payload: {showTitle: value}})
  // }

  // 审批意见
  const handleAdviceChange = (value) => {
    dispatch({ type: `${domain}/updateState`, payload: { advice: value } });
  };

  // 按钮绑定点击事件
  if (remoteCfg) {
    const remoteBtns = remoteCfg.buttons;
    remoteBtns.length > 0 && remoteBtns.map(btn => {
      if (btn.id === 'confirm') { // 确认保存
        btn.onClick = () => dispatch({ type: 'purchasingOrderDetails/save' });
      }
      if (btn.id === 'approve') { // 审批通过
        btn.onClick = () => dispatch({ type: 'purchasingOrderDetails/approve' });
      }
      if (btn.id === 'reject') { // 审批拒绝
        btn.onClick = () => dispatch({ type: 'purchasingOrderDetails/reject' });
      }
      if (btn.id === 'cancel') { // 审批作废
        btn.onClick = () => dispatch({ type: 'purchasingOrderDetails/cancel' });
      }
    });

    const buttons = [
      // {
      // id: 'confirm',
      // text: '确认', // 保存
      // type: 'primary',
      // hidden: !editable,
      // onClick: handleSave
      // }, {
      //   id: 'approve',
      //   text: '同意',
      //   type: 'primary',
      //   hidden: !flowModuleShow,
      //   onClick: handleApprove
      // }, {
      //   id: 'reject',
      //   text: '拒绝',
      //   hidden: !flowModuleShow,
      //   onClick: handleReject
      // },
      {
        id: 'advice',
        text: '审批意见',
        hidden: !flowModuleShow,
        onChange: (e) => {
          handleAdviceChange(e.target.value);
        },
      },
      ...remoteBtns,
    ];

    return (
      <div style={{ height: '100%' }}>
        {
          Object.keys(formData).length > 0 &&
          <Toolbar
            domain={domain}
            loading={loading}
            record={formData}
            readOnly={readOnly}
            mode={mode}
            buttons={buttons}
            // handleSave={handleSave}
            handleCancel={handleCancel}
            prcId={formData.prcId}
            defId={formData.defId}
          />
        }

        {
          Object.keys(formData).length > 0 &&
          <CollapseEL>
            <Card
              id="basic"
              // title={showTitle ? `基本信息 ( 采购单编号:${formData.docNo} / 供应商名称:${formData.suppName} )` : '基本信息'}
              title='基本信息'
              loading={loading.effects[`${domain}/query`]}
            >
              <FormEL
                items={basic}
                record={formData}
                readOnly={readOnly}
                onFieldsChange={handleFormChange}
              />
            </Card>
          </CollapseEL>
        }

        {
          list.length > 0 &&
          <Card
            id="material"
            title="采购单明细列表"
            loading={loading.effects[`${domain}/query`]}
          >
            <EditableDataTable {...tableProps} />
          </Card>
        }
      </div>);
  } else {
    return <Loader fullScreen={false} spinning={loading.effects[`${domain}/querySingle`]}/>;
  }
};

export default connect(({ purchasingOrderDetails, ouBanks, loading, app }) => ({
  purchasingOrderDetails,
  loading,
  app,
}))(Detail);
