import { DatePicker, Input, Table, Popover, Button, Row, Col, InputNumber } from 'antd';
import { connect } from 'dva';
import React from 'react';

import { DataTable, UdcSelect, SuggestSelect } from '@components';
import { config } from '@utils';
import { numberUtils } from '@utils';

import styles from './expandedRow.less';

const { RangePicker } = DatePicker;
const { api } = config;
const { excel } = api;
const { exportExcelURL } = excel;

const StockInOrderForm = ({ dispatch, stockInOrderForm, loading, app }) => {
  const { list, total, diffData, editable } = stockInOrderForm;
  const { user } = app.user;

  const domain = 'stockInOrderForm';
  const domainCN = '入库单列表';

  const handelCellValue = (key, index, value, pIndex) => {
    dispatch({
      type: `${domain}/saveDetail`,
      payload: { key, index, value, pIndex }
    });
  };

  class StockPopover extends React.Component {
    constructor(props) {
      super(props)

      this.state = {
        visible: false,
        popInputValue: props.value,
        initialValue: props.value,
      }

    }

    hide = () => {
      const { initialValue } = this.state;
      this.setState({
        visible: false,
        popInputValue: initialValue
      });
    }

    handleVisibleChange = (visible) => {
      const { initialValue } = this.state;
      this.setState({
        visible,
        popInputValue: initialValue
      });
    }

    confirmSave = () => {
      const value = this.state.popInputValue;
      const { keyName, index, record } = this.props;

      handelCellValue(keyName, index, value, list.indexOf(record));
      this.hide();
    }

    render() {
      const { title, value ,keyName} = this.props;
      const { visible, popInputValue } = this.state;
      let inputProps = {
        style: { width: '100%' },
        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, ''),
        maxLength: 19,
      }
      if(keyName==='deliPrice'){
        inputProps={...inputProps,precision:4,step:0.0001}
      }
      return (<Popover
        placement="top"
        content={
          <div style={{ width: 150 }}>
            <InputNumber
              value={popInputValue}
              onChange={value => {
                this.setState({
                  popInputValue: value,
                })
              }}
              {...inputProps} />
            <Row gutter={24} style={{ marginTop: 5 }}>
              <Col span={12}>
                <Button size="small" style={{ width: '100%' }} type="primary" onClick={this.confirmSave}>确认</Button>
              </Col>
              <Col span={12}>
                <Button size="small" style={{ width: '100%' }} onClick={this.hide}>取消</Button>
              </Col>
            </Row>
          </div>
        }
        title={title}
        trigger="click"
        visible={visible}
        onVisibleChange={this.handleVisibleChange}
      >
        <span style={{ color: 'blue' }}>{value}</span>
      </Popover>);
    }
  }


  const expandedRowRender = (record) => {
    const firstColumns = [{
      title: '物料编号',
      dataIndex: 'itemCode',
      className: 'noWrap',
      key: 'itemCode'
    }, {
      title: '物料名称',
      dataIndex: 'itemName',
      key: 'itemName'
    }, {
      title: '物料规格',
      dataIndex: 'spec',
      key: 'spec'
    }, {
      title: '单位',
      dataIndex: 'uom',
      key: 'uom',
    }, {
      title: '采购数量',
      dataIndex: 'poQty',
      key: 'poQty',
      className: 'alignRight',
    }, {
      title: '承诺数量',
      dataIndex: 'promiseQty',
      key: 'promiseQty',
      className: 'alignRight',
    }, {
      title: '实收数量',
      dataIndex: 'qty',
      key: 'qty',
      className: 'alignRight',
    }];

    const secondColumns = [{
      title: '实际数量',
      dataIndex: 'deliQty',
      key: 'deliQty',
      className: 'alignRight',
      render: (value, row, index) => {
        const disabled = editable && !row.accountNo && row.rowEditable === 'D';
        return (disabled ? <StockPopover value={value} title="实际数量" record={record} keyName="deliQty" index={index} /> : value)
      }
    }, {
      title: '实际单价',
      dataIndex: 'deliPrice',
      key: 'deliPrice',
      className: 'alignRight',
      render: (value, row, index) => {
        const disabled = editable && !row.accountNo && row.rowEditable === 'D';
        value=numberUtils.round_half_up_format(value,4);
        return (disabled ? <StockPopover value={value} title="实际单价" record={record} keyName="deliPrice" index={index} /> : value)
      }
    }, {
      title: '实际总价',
      dataIndex: 'deliAmt',
      key: 'deliAmt',
      className: 'alignRight',
      render: (value, row, index) => {
        return numberUtils.round_half_up_format(value,2)
      }
    }, {
      title: '差异数量',
      dataIndex: 'diffQty',
      key: 'diffQty',
      className: 'alignRight',
    }, {
      title: '差异单价',
      dataIndex: 'diffPrice',
      key: 'diffPrice',
      className: 'alignRight',
      render: (value, row, index) => {
        return numberUtils.round_half_up_format(value,4)
      }
    }, {
      title: '差异总价',
      dataIndex: 'differenceAmt',
      key: 'differenceAmt',
      className: 'alignRight',
      render: (value, row, index) => {
        return numberUtils.round_half_up_format(value,2)
      }
    }];

    const thirdColumns = [{
      title: '含税单价',
      dataIndex: 'price',
      key: 'price',
      className: 'alignRight',
      render: (value, row, index) => {
        return numberUtils.round_half_up_format(value,4)
      }
    }, {
      title: '未税总价',
      dataIndex: 'netAmt',
      key: 'netAmt',
      className: 'alignRight',
      render: (value, row, index) => {
        return numberUtils.round_half_up_format(value,2)
      }
    }, {
      title: '含税总价',
      dataIndex: 'amt',
      key: 'amt',
      className: 'alignRight',
      render: (value, row, index) => {
        return numberUtils.round_half_up_format(value,2)
      }
    }, {
      title: '税率(%)',
      dataIndex: 'taxRate',
      key: 'taxRate',
      className: 'alignRight',
    }, {
      title: '税额',
      dataIndex: 'taxAmt',
      key: 'taxAmt',
      className: 'alignRight',
      render: (value, row, index) => {
        return numberUtils.round_half_up_format(value,2)
      }
    }, {
      title: '对账单号',
      dataIndex: 'accountNo',
      className: 'noWrap',
      key: 'accountNo',
    }, {
      title: '发票号码',
      dataIndex: 'invNo',
      className: 'noWrap',
      key: 'invNo',
    }, {
      title: '仓库名称（编码）',
      dataIndex: 'whName',
      key: 'whName',
      render: (value, row) => {
        return (row.whName && row.whCode) ? `${row.whName}（${row.whCode}）` : ''
      }
    }, {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
    }];

    const columns = diffData ? firstColumns.concat(secondColumns, thirdColumns) : firstColumns.concat(thirdColumns);

    return (
      <Table
        size="small"
        rowKey='id'
        columns={columns}
        dataSource={record.details}
        pagination={false}
      />
    );
  };

  const tableProps = {
    rowKey: 'id',
    scroll: {
      x: diffData ? '180%' : '150%',
      y: 400,
    },
    sortBy: 'docNo',
    sortDirection: 'DESC',
    domain,
    dispatch,
    loading,
    showAdd: false,
    showDelete: false,
    showEdit: false,
    total,
    dataSource: list,
    expandedRowRender,
    enableSelection: false,
    handleDownload: {
      requestUrl: `${exportExcelURL}/recp`,
      requestParam: window.location.search,
    },
    filter: [{
      title: '入库单编号',
      dataIndex: 'docNo',
      tag: <Input placeholder='请输入编号' />,
    }, {
      title: '入库日期',
      dataIndex: 'recpDate',
      tag: <RangePicker style={{ width: '100%' }} />,
    }, {
      title: '供应商',
      dataIndex: 'suppCodeName',
      options: {
        initialValue: (user.entType === 'supp' && user.name) || '',
      },
      tag: <Input placeholder='请输入编号/名称' disabled={user.entType === 'supp'} />,
    }, {
      title: '入库单位',
      dataIndex: 'recpOuCodeName',
      options: {
        initialValue: '',
      },
      tag: <Input placeholder='请输入编号/名称' />,
    }, {
      // 用于供应商等picker组件精确查询
      //   title: '供应商',
      //   dataIndex: 'suppId',
      //   options: {
      //     initialValue: '',
      //   },
      //   tag: <SupplierPicker />,
      // }, {
      //   title: '入库单位',
      //   dataIndex: 'recpOuId',
      //   options: {
      //     initialValue: '',
      //   },
      //   tag: <OuPicker />,
      // }, {
      title: '采购单编号',
      dataIndex: 'poNo',
      tag: <Input placeholder='请输入采购单编号' />,
    }, {
      title: '仓库',
      dataIndex: 'whCode',
      tag: <Input placeholder='请输入仓库编号/名称' />,
    }, {
      title: '有无差异',
      dataIndex: 'diffType',
      tag: <UdcSelect domain="SRM" code="RECP_DIFF_TYPE" />,
    }, {
      title: '来源类型',
      dataIndex: 'docType',
      tag: <UdcSelect domain="SRM" code="RECP_BU_TYPE" />,
    }, {
      title: '对账状态',
      dataIndex: 'checkStatus',
      tag: <UdcSelect domain="SRM" code="RECP_ACOUNT_STATUS" />,
    }, {
      title: '收货门店',
      dataIndex: 'outerShans',
      tag: <SuggestSelect apiName="outShans" mode="multiple" optionKey="code"/>,
    }],
    columns: [{
      title: '采购单编号',
      dataIndex: 'poNo',
      className: 'noWrap',
      width: '10%',
      sorter: true,
    }, {
      title: '入库单编号',
      dataIndex: 'docNo',
      className: 'noWrap',
      width: '10%',
      sorter: true,
    }, {
      title: '入库单类型',
      dataIndex: 'docTypeName',
      // className: 'noWrap',
      width: '6%',
      // sorter: true,
    }, {
      title: '供应商编号',
      dataIndex: 'suppCode',
      width: '8%',
      sorter: true,
    }, {
      title: '供应商名称',
      dataIndex: 'suppName',
      width: '13%',
      className: 'alignLeft',
      sorter: true,
    }, {
      title: '含税金额',
      dataIndex: 'amt',
      width: '7%',
      className: 'alignRight',
      sorter: true,
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value,2)
        )
      }
    }, {
      title: '未税金额',
      dataIndex: 'netAmt',
      width: '7%',
      className: 'alignRight',
      sorter: true,
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value,2)
        )
      }
    }, {
      title: '税额',
      dataIndex: 'taxAmt',
      width: '5%',
      className: 'alignRight',
      sorter: true,
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value,2)
        )
      }
    },
    //  {
    //   title: '入库单状态',
    //   dataIndex: 'docStatusName',
    //   width: '6%',
    //   // sorter: true,
    // },
    {
      title: '入库日期',
      dataIndex: 'recpDate',
      className: 'noWrap',
      width: '7%',
      sorter: true,
    }, {
      title: '入库单位',
      dataIndex: 'recpOuName',
      width: '10%',
      className: 'alignLeft',
      sorter: true,
    }, {
      title: '入库地址',
      dataIndex: 'recpAddr',
      width: '10%',
      className: 'alignLeft',
      sorter: true,
    },{
      title: '收货门店',
      dataIndex: 'outerShanCodeAndName',
      width: '10%',
      className: 'alignLeft',
    }],
    buttons: [{
      key: 'create',
      type: 'primary',
      name: diffData ? '隐藏差异' : '显示差异',
      requiredSelected: 0,
      cb: (selectedKeys) => {
        dispatch({
          type: `${domain}/showDiffData`,
        });
      },
    }],
  };

  return (
    <div className={['content-inner', styles['table-expanded-row']].join(' ')}>
      <DataTable {...tableProps} />
    </div>
  );

};

export default connect(({ stockInOrderForm, loading, app }) => ({ stockInOrderForm, loading, app }))(StockInOrderForm);
