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

import { DataTable, SuggestSelect, UdcSelect } from '@components';
import { config, stringUtils, theme } from '@utils';
import { numberUtils } from '@utils';
import styles from './expandedRow.less';

const dateFormat = 'YYYY-MM-DD';

const { RangePicker } = DatePicker;
const confirm = Modal.confirm;

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

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

const PurchasingOrderForm = ({ dispatch, purchasingOrderForm, loading, app }) => {
  const { list, total, confirmHidden, approvalHidden } = purchasingOrderForm;
  const { user } = app.user;

  const docDateFrom = stringUtils.queryURL('docDateFrom');
  const docDateTo = stringUtils.queryURL('docDateTo');
  const demandDateFrom = stringUtils.queryURL('demandDateFrom');
  const demandDateTo = stringUtils.queryURL('demandDateTo');

  // const reqDateFrom = stringUtils.queryURL('reqDateFrom');
  // const reqDateTo = stringUtils.queryURL('reqDateTo');
  // const suppId = {
  //   id: stringUtils.queryURL('suppId'),
  //   code: stringUtils.queryURL('suppCode'),
  //   name: stringUtils.queryURL('suppName'),
  // }
  // const acceptOuId = {
  //   id: stringUtils.queryURL('acceptOuId'),
  //   code: stringUtils.queryURL('acceptOuCode'),
  //   name: stringUtils.queryURL('acceptOuName'),
  // }

  const domain = 'purchasingOrderForm';
  const domainCN = '采购订单列表';

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

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

  const handleExpandRowClick = (expanded, record) => {
    if (!record.expanded) {
      dispatch({ type: `${domain}/getDetails`, payload: { expanded, record } });
    }
  };

  const expandedRowRender = (record) => {
    const columns = [{
      title: '物料编号',
      dataIndex: 'itemCode',
      key: 'itemCode',
      width: '7%'
    }, {
      title: '物料名称',
      dataIndex: 'itemName',
      key: 'itemName',
      className: 'alignLeft',
      width: '9%'
    }, {
      title: '规格',
      dataIndex: 'spec',
      key: 'spec',
      width: '6%'
    }, {
      title: '单位',
      dataIndex: 'uom',
      key: 'uom',
      width: '4%'
    }, {
      title: '采购数量',
      dataIndex: 'qty',
      key: 'qty',
      className: 'alignRight',
      width: '6%'
    }, {
      title: '承诺数量',
      dataIndex: 'promiseQty',
      key: 'promiseQty',
      width: '7%',
      render: (value, row, index) => {
        const rowData = list[list.indexOf(record)];
        const uneditable = row.qty < 0 || rowData.docStatus !== '290' || user.entType !== 'supp' || rowData.docType !== 'OP' || rowData.approveStatus !== '00';
        return (
          <InputNumber
            size="small"
            value={value}
            max={999999999999}
            disabled={uneditable}
            formatter={value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
            parser={value => value.replace(/\$\s?|(,*)/g, '')}
            onChange={(value) => handleUpdateValue(index, 'promiseQty', value, list.indexOf(record), 999999999999)}
          />
        );
      }
    }, {
      title: '数量差异',
      dataIndex: 'diffQty',
      key: 'diffQty',
      className: 'alignRight',
      width: '6%',
      render: (value) => {
        return (<span style={{ color: theme.color.deepRed }}>{value}</span>);
      }
    }, {
      title: '未税单价',
      dataIndex: 'netPrice',
      key: 'netPrice',
      className: 'alignRight',
      width: '7%',
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value,4)
        );
      }
    }, {
      title: '含税单价',
      dataIndex: 'price',
      key: 'price',
      className: 'alignRight',
      width: '7%',
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value,4)
        );
      }
    }, {
      title: '未税总价',
      dataIndex: 'netAmt',
      key: 'netAmt',
      className: 'alignRight',
      width: '7%',
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value,2)
        );
      }
    }, {
      title: '含税总价',
      dataIndex: 'amt',
      key: 'amt',
      className: 'alignRight',
      width: '7%',
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value,2)
        );
      }
    }, {
      title: '税率(%)',
      dataIndex: 'taxRate',
      key: 'taxRate',
      className: 'alignRight',
      width: '5%'
    }, {
      title: '税额',
      dataIndex: 'taxAmt',
      key: 'taxAmt',
      className: 'alignRight',
      width: '7%',
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value,2)
        );
      }
    }, {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      className: 'alignLeft',
      width: '23%'
    }];

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

  // 单个复选框选中
  const checkBoxOnSelect = (record, selected, selectedRows) => {
    checkConfirmHidden(selectedRows); // 确认按钮
  };

  // 复选框全部选中
  const checkBoxOnSelectAll = (selected, selectedRows) => {
    checkConfirmHidden(selectedRows); // 确认按钮
  };

  // 判断按钮是否可见
  const checkConfirmHidden = (selectedRows) => {
    let hasError = false;
    if (selectedRows.length > 0) {

      // 控制审批按钮
      if (selectedRows[0].docStatus === '300') {
        dispatch({type: 'purchasingOrderForm/updateState', payload: {approvalHidden: true}});
      } else {
        dispatch({type: 'purchasingOrderForm/updateState', payload: {approvalHidden: false}});
      }

      selectedRows.map(row => {
        if (row.docStatus !== '290' || user.entType !== 'supp' || row.docType !== 'OP' || row.approveStatus !== '00') {
          hasError = true;
        }
      });
    }
    if (hasError) {
      dispatch({ type: 'purchasingOrderForm/updateState', payload: { confirmHidden: true } });
    } else {
      dispatch({ type: 'purchasingOrderForm/updateState', payload: { confirmHidden: false } });
    }
  };

  // const

  const tableProps = {
    rowKey: 'id',
    scroll: {
      x: '210%',
      y: 400,
    },
    limit: stringUtils.queryURL('limit'),
    offset: stringUtils.queryURL('offset'),
    domain,
    dispatch,
    loading,
    showAdd: false,
    showDelete: false,
    showEdit: false,
    total,
    dataSource: list,
    expandedRowRender,
    rowSelection: {
      type: 'checkbox',
      onSelect: checkBoxOnSelect,
      onSelectAll: checkBoxOnSelectAll,
    },
    handleDownload: {
      requestUrl: `${exportExcelURL}/po`,
      requestParam: window.location.search,
    },
    // onExpand: handleExpandRowClick,
    filter: [{
      title: '采购单据编号',
      dataIndex: 'docNo',
      options: {
        initialValue: stringUtils.queryURL('docNo') || ''
      },
      tag: <Input placeholder='请输入编号' />,
    }, {
      title: '采购单状态',
      dataIndex: 'docStatus',
      options: {
        initialValue: stringUtils.queryURL('docStatus')
      },
      tag: <UdcSelect domain="SRM" code="PO_STATUS" />,
    }, {
      title: '采购员',
      dataIndex: 'poAgent',
      options: {
        initialValue: stringUtils.queryURL('poAgent') || ''
      },
      tag: <Input placeholder='请输入采购员编号/名称' />,
    }, {
      title: '制单日期',
      dataIndex: 'docDate',
      options: {
        initialValue: docDateFrom ? [moment(docDateFrom, dateFormat), moment(docDateTo, dateFormat)] : []
      },
      tag: <RangePicker format="YYYY-MM-DD" style={{ width: '100%' }} />,
    }, {
      title: '要求到货日期',
      dataIndex: 'demandDate',
      options: {
        initialValue: demandDateFrom ? [moment(demandDateFrom, dateFormat), moment(demandDateTo, dateFormat)] : []
      },
      tag: <RangePicker format="YYYY-MM-DD" style={{ width: '100%' }} />,
    }, {
      title: '供应商',
      dataIndex: 'suppCodeName',
      options: {
        initialValue: (user.entType === 'supp' && user.name) || stringUtils.queryURL('suppCodeName'),
      },
      tag: <Input placeholder='请输入编号/名称' disabled={user.entType === 'supp'} />,
    }, {
      title: '收货单位',
      dataIndex: 'acceptOuCodeName',
      options: {
        initialValue: stringUtils.queryURL('acceptOuCodeName'),
      },
      tag: <Input placeholder='请输入编号/名称' />,
    }, {
      title: '任务节点',
      dataIndex: 'activeTaskKey',
      options: {
        initialValue: stringUtils.queryURL('activeTaskKey'),
      },
      tag: <SuggestSelect apiName="taskDefs" params={{ defKeys: ['PurchasingOrder'] }} optionKey="code" />,
    }, {
      title: '流程状态',
      dataIndex: 'bpmStatus',
      options: {
        initialValue: stringUtils.queryURL('bpmStatus') || 'NONE',
      },
      tag: <UdcSelect domain="SRM" code="TRANSACT_STATUS" />,
      // 用于供应商等Picker组件精确查询
      //   title: '供应商',
      //   dataIndex: 'suppId',
      //   options: {
      //     initialValue: stringUtils.queryURL('suppId') ? suppId : '',
      //   },
      //   tag: <SupplierPicker />,
      // }, {
      //   title: '收货单位',
      //   dataIndex: 'acceptOuId',
      //   options: {
      //     initialValue: stringUtils.queryURL('acceptOuId') ? acceptOuId : '',
      //   },
      //   tag: <OuPicker />,
      // }, {
    }],
    columns: [{
      title: '采购单据编号',
      dataIndex: 'docNo',
      width: '7%',
      // className: 'noWrap',
      sorter: true,
    }, {
      title: '采购单状态',
      dataIndex: 'docStatusName',
      width: '5%',
      // sorter: true,
    }, {
      title: '供应商',
      dataIndex: 'suppName',
      width: '12%',
      className: 'alignLeft',
      sorter: true,
    }, {
      title: '承诺交货期间',
      dataIndex: 'promisePeriod',
      width: '14%',
      sorter: true,
      // className: 'noWrap',
      render: (value, row, index) => {
        const { promiseDate, deliveryTimeFrom, deliveryTimeTo } = value;
        const editable = row.docStatus === '290' && user.entType === 'supp' && row.docType === 'OP' && row.approveStatus === '00';
        return (
          <>
            <DatePicker
              size="small"
              disabledDate={disabledStartDate}
              value={promiseDate && moment(promiseDate, dateFormat)}
              style={{ width: '50%' }}
              disabled={!editable}
              onChange={(date, dateString) => handleDateChange(dateString, 'promiseDate', index)}
            />
            <TimePicker
              size="small"
              value={deliveryTimeFrom && moment(deliveryTimeFrom, 'HH:mm')}
              format={'HH:mm'}
              style={{ width: '25%' }}
              className={'deliveryTimeFrom'}
              disabled={!editable}
              onChange={(time, timeString) => handleDateChange(timeString, 'deliveryTimeFrom', index)}
            />
            <TimePicker
              size="small"
              value={deliveryTimeTo && moment(deliveryTimeTo, 'HH:mm')}
              format={'HH:mm'}
              style={{ width: '25%' }}
              className={'deliveryTimeTo'}
              disabled={!editable}
              onChange={(time, timeString) => handleDateChange(timeString, 'deliveryTimeTo', index)}
            />
          </>
        );
      },
      // title: '承诺交货日期',
      // dataIndex: 'promiseDate',
      // width: '9%',
      // sorter: true,
      // className: 'noWrap',
      // render: (value, row, index) => {
      //   const {promiseDate, deliveryTimeFrom, deliveryTimeTo} = value
      //   return (
      //     <>
      //       <DatePicker
      //         disabledDate={disabledStartDate}
      //         value={value && moment(value, dateFormat)}
      //         // style={{ width: '100%' }}
      //         onChange={(dateString) => handelDateChange(dateString, 'promiseDate', index)}
      //       />
      //       <TimePicker defaultValue={moment('12:08', 'HH:mm')} format={'HH:mm'} />
      //       <TimePicker defaultValue={moment('20:08', 'HH:mm')} format={'HH:mm'} />
      //     </>
      //   )
      // },
    }, {
      title: '要求到货日期',
      dataIndex: 'demandDate',
      width: '7%',
      sorter: true,
    }, {
      //   title: '期望到货日期',
      //   dataIndex: 'reqDate',
      //   width: '7%',
      //   sorter: true,
      // }, {
      title: '有无差异',
      dataIndex: 'hasDiff',
      width: '3%',
      render: (value, row, index) => {
        return (<span style={{ color: theme.color.deepRed }}>{value ? '有' : '无'}</span>);
      },
    }, {
      title: '收货单位',
      dataIndex: 'acceptOuName',
      width: '11%',
      className: 'alignLeft',
      sorter: true,
    }, {
      title: '未税金额',
      dataIndex: 'netAmt',
      width: '5%',
      className: 'alignRight',
      sorter: true,
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value,2)
        );
      }
    }, {
      title: '含税金额',
      dataIndex: 'amt',
      width: '5%',
      className: 'alignRight',
      sorter: true,
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value,2)
        );
      }
    }, {
      title: '税额',
      dataIndex: 'taxAmt',
      width: '4%',
      className: 'alignRight',
      sorter: true,
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value,2)
        );
      }
      // }, {
      //   title: '运输方式',
      //   dataIndex: 'deliveryTypeName',
      //   width: '4%',
      //   className: 'alignLeft',
      //   sorter: true,
    }, {
      title: '采购员',
      dataIndex: 'poAgentName',
      width: '5%',
      sorter: true,
    }, {
      title: '制单人员',
      dataIndex: 'createUserName',
      width: '5%',
      sorter: true,
    }, {
      title: '制单日期',
      dataIndex: 'docTime',
      width: '6%',
      sorter: true,
    }, {
      title: '当前任务',
      dataIndex: 'activeTaskName',
      className: 'alignLeft',
      width: '8%',
    }],
    buttons: [{
      key: 'confirm',
      type: 'primary',
      name: '确认',
      requiredSelected: 2,
      hidden: confirmHidden,
      cb: (selectedRowKeys) => {
        confirm({
          title: '是否确定提交?',
          okText: '确定',
          okType: 'danger',
          cancelText: '取消',
          onOk() {
            dispatch({ type: 'purchasingOrderForm/confirm', payload: selectedRowKeys });
          },
        });
      },
      // TODO: 暂时注掉，以后可能会批量使用
      // }, {
      //   key: 'batchApprove',
      //   type: 'primary',
      //   name: '批量同意',
      //   requiredSelected: 2,
      //   cb: (selectedRowKeys) => {
      //     confirm({
      //       title: '是否批量同意?',
      //       okText: '确定',
      //       okType: 'danger',
      //       cancelText: '取消',
      //       onOk() {
      //         dispatch({ type: 'purchasingOrderForm/batchApprove', payload: selectedRowKeys })
      //       },
      //     });
      //   },
      // }, {
      //   key: 'batchReject',
      //   type: 'primary',
      //   name: '批量拒绝',
      //   requiredSelected: 2,
      //   cb: (selectedRowKeys) => {
      //     confirm({
      //       title: '是否批量拒绝?',
      //       okText: '确定',
      //       okType: 'danger',
      //       cancelText: '取消',
      //       onOk() {
      //         dispatch({ type: 'purchasingOrderForm/batchReject', payload: selectedRowKeys })
      //       },
      //     });
      //   },
    }, {
      key: 'approve',
      type: 'primary',
      name: '采购单审批',
      requiredSelected: 1,
      hidden: approvalHidden,
      cb: (selectedKeys) => {
        dispatch({
          type: `${domain}/getSingle`,
          payload: {
            id: selectedKeys[0],
            mode: 'approval',
          },
        });
      },
    }],
  };

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

};

export default connect(({ purchasingOrderForm, loading, app }) => ({ purchasingOrderForm, loading, app }))(PurchasingOrderForm);
