import { Input, DatePicker, Tooltip, Modal } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import ModalView from './Modal';
import React from 'react';
import { DataTable, UdcSelect, SuggestSelect } from '@components';
import { stringUtils, config } from '@utils';
import { numberUtils } from '@utils';

let startMonth = null, endMonth = null;
const handleChangeForm = (field, value) => {
  startMonth = field;
};

const handleChangeTo = (field, value) => {
  endMonth = field;
};

const disabledDateForm = (currentDate) => {
  if (!endMonth) {
    return false;
  }
  return endMonth.endOf('month') <= currentDate;
};

const disabledDateTo = (currentDate) => {
  if (!startMonth) {
    return false;
  }
  return startMonth >= currentDate;
};

const handleExport = (url) => {
  const a = document.createElement('a');
  // a.style = 'display: none';
  a.style.display = 'none';
  // a.download = fileName;
  a.href = url;
  a.target = '_blank';

  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
};

const { api } = config;
const { excel } = api;
const { exportExcelURL } = excel;
const { MonthPicker } = DatePicker;
const Accounts = ({ dispatch, accounts, loading }) => {
  const { list, total, createBtn, editBtn, modalVisible, suppId, invoiceBtn, approvalBtn, reAccBtn } = accounts;
  const domain = 'accounts';
  const tableProps = {
    rowKey: 'id',
    sortBy: 'id',
    limit: stringUtils.queryURL('limit'),
    offset: stringUtils.queryURL('offset'),
    sortDirection: 'DESC',
    scroll: {
      x: '170%',
      y: 400,
    },
    domain,
    dispatch,
    loading,
    showAdd: false,
    showEdit: false,
    showView: false,
    showDelete: false,
    enableDoubleClick: false,
    // rowSelection: {
    //   onSelect: (record, selected, selectedRows, selectedRowKeys) => {
    //     // 如果审批退回第一个节点，则修改审批按钮名称
    //     if (selectedRows[0].taskKey === 'initiator') {
    //       dispatch({
    //         type: `${domain}/updateState`,
    //         payload: {
    //           approvalBtnName: '退单修改',
    //         },
    //       });
    //     } else {
    //       dispatch({
    //         type: `${domain}/updateState`,
    //         payload: {
    //           approvalBtnName: '审批对账单',
    //         },
    //       });
    //     }
    //   },
    // },
    total,
    dataSource: list,
    handleDownload: {
      requestUrl: `${exportExcelURL}/account`,
      requestParam: window.location.search,
    },
    filter: [{
      title: '对账单编号',
      dataIndex: 'docNo',
      options: {
        initialValue: stringUtils.queryURL('docNo'),
      },
    }, {
      title: '对账单状态',
      dataIndex: 'status',
      tag: <UdcSelect domain="SRM" code="ACCOUNT_CHECK_STATUS" />,
      options: {
        initialValue: stringUtils.queryURL('status'),
      },
    }, {
      title: '形式发票编号',
      dataIndex: 'invNo',
      options: {
        initialValue: stringUtils.queryURL('invNo'),
      },
    }, {
      title: '对账差异',
      dataIndex: 'diffFlag',
      tag: <UdcSelect domain="SRM" code="DIFF_FLAG" />,
      options: {
        initialValue: stringUtils.queryURL('diffFlag'),
      },
    }, {
      title: '供应商名称',
      dataIndex: 'suppCode',
      tag: <Input placeholder="请输入名称/编号" />,
      options: {
        initialValue: stringUtils.queryURL('suppCode'),
      },
    }, {
      title: '企业名称',
      dataIndex: 'ouCode',
      tag: <Input placeholder="请输入名称/编号" />,
      options: {
        initialValue: stringUtils.queryURL('ouCode'),
      },
    }, {
      title: '账期(起)',
      dataIndex: 'payPeriodFromDate',
      tag: (<MonthPicker placeholder="请选择月份" style={{ width: '100%' }} onChange={handleChangeForm} disabledDate={disabledDateForm} />),
      options: {
        initialValue: stringUtils.queryURL('payPeriodFromDate') ? moment(stringUtils.queryURL('payPeriodFromDate')) : null,
      },
    }, {
      title: '账期(止)',
      dataIndex: 'payPeriodToDate',
      tag: (<MonthPicker placeholder="请选择月份" style={{ width: '100%' }} onChange={handleChangeTo} disabledDate={disabledDateTo} />),
      options: {
        initialValue: stringUtils.queryURL('payPeriodToDate') ? moment(stringUtils.queryURL('payPeriodToDate')) : null,
      },
    }, {
      title: '任务节点',
      dataIndex: 'activeTaskKey',
      options: {
        initialValue: stringUtils.queryURL('activeTaskKey'),
      },
      tag: <SuggestSelect apiName="taskDefs" params={{ defKeys: ['AccountCheck'] }} optionKey="code" />,
    }, {
      title: '流程状态',
      dataIndex: 'bpmStatus',
      options: {
        initialValue: stringUtils.queryURL('bpmStatus'),
      },
      tag: <UdcSelect domain="SRM" code="TRANSACT_STATUS" />,
    }],
    columns: [{
      title: '企业名称',
      dataIndex: 'ouName',
      className: 'alignLeft',
      width: '10%',
      sorter: true,
      render: (value) => {
        if (value) {
          return value.length > 10 ? <Tooltip placement="bottom" title={value}>
            {value && `${value.slice(0, 10)}...`}
          </Tooltip> : value;
        } else {
          return '无';
        }
      },
    }, {
      title: '对账单编号',
      dataIndex: 'docNo',
      width: '9%',
      sorter: true,
    }, {
      title: '形式发票编号',
      dataIndex: 'invNo',
      width: '9%',
      sorter: true,
    }, {
      title: '供应商编号',
      dataIndex: 'suppCode',
      width: '5%',
      sorter: true,
    }, {
      title: '供应商名称',
      dataIndex: 'suppName',
      className: 'alignLeft',
      width: '10%',
      sorter: true,
      render: (value) => {
        if (value) {
          return value.length > 10 ? <Tooltip placement="bottom" title={value}>
            {value && `${value.slice(0, 10)}...`}
          </Tooltip> : value;
        } else {
          return '无';
        }
      },
    }, {
      title: '对账日期',
      dataIndex: 'docDate',
      className: 'noWrap',
      width: '6%',
      sorter: true,
    }, {
      title: '账期',
      dataIndex: 'payPeriod',
      width: '4%',
      sorter: true,
    }, {
      title: '对账单状态',
      dataIndex: 'statusDesc',
      width: '4%',
    }, {
      title: '审批状态',
      dataIndex: 'approveStatusDesc',
      width: '4%',
    }, {
      title: '含税总额',
      dataIndex: 'amt',
      width: '6%',
      className: 'alignRight',
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value, 2)
        );
      }
    }, {
      title: '未税总额',
      dataIndex: 'netAmt',
      width: '6%',
      className: 'alignRight',
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value, 2)
        );
      }
    }, {
      title: '税额',
      dataIndex: 'taxAmt',
      width: '5%',
      className: 'alignRight',
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value, 2)
        );
      }
    }, {
      title: '对账差异',
      dataIndex: 'diffFlagDesc',
      width: '4%',
    }, {
      title: '对账开始日期',
      dataIndex: 'payFromDate',
      className: 'noWrap',
      width: '6%',
    }, {
      title: '对账结束日期',
      dataIndex: 'payToDate',
      className: 'noWrap',
      width: '6%',
    }, {
      title: '当前任务',
      dataIndex: 'activeTaskName',
      className: 'alignLeft',
      width: '6%',
    }],
    buttons: [{
      key: 'view',
      type: 'primary',
      name: '查看',
      requiredSelected: 1,
      cb: (selectedKeys) => {
        dispatch({
          type: `${domain}/getSingle`,
          payload: {
            mode: 'view',
            id: selectedKeys[0],
          },
        });
      },
    }, {
      key: 'create',
      type: 'primary',
      name: '新建对账单',
      hidden: createBtn,
      requiredSelected: 0,
      cb: (selectedKeys) => {
        dispatch({
          type: `${domain}/showPop`,
        });
      },
    }, {
      key: 'update',
      type: 'primary',
      name: '编辑对账单',
      hidden: editBtn,
      requiredSelected: 1,
      cb: (selectedKeys, searchBarForm, selectedRows) => {
        dispatch({
          type: `${domain}/getSingle`,
          payload: {
            mode: 'update',
            account: selectedRows[0],
          },
        });
      },
    }, {
      key: 'approval',
      type: 'primary',
      name: '审批对账单',
      hidden: approvalBtn,
      requiredSelected: 1,
      cb: (selectedKeys) => {
        dispatch({
          type: `${domain}/goToApproval`,
          payload: {
            mode: 'approval',
            id: selectedKeys[0],
          },
        });
      },
    }, {
      key: 'reAcc',
      type: 'primary',
      name: '重新对账',
      hidden: reAccBtn,
      requiredSelected: 1,
      cb: (selectedKeys) => {
        Modal.confirm({
          title: '确认要重新对账吗',
          content: '如果已经新建发票，重新对账会删除所有未提交的发票',
          okText: '确认',
          onOk() {
            dispatch({
              type: `${domain}/reAcc`,
              payload: {
                id: selectedKeys[0],
              },
            });
          },
          cancelText: '取消',
          onCancel() {
          },
        });
      },
    }, {
      key: 'creatInv',
      type: 'primary',
      name: '开票',
      hidden: invoiceBtn,
      requiredSelected: 1,
      cb: (selectedRowKeys, searchBarForm, selectedRows) => {
        dispatch({
          type: `${domain}/goToFormaInvoice`,
          payload: {
            selectedRowKeys,
            selectedRows
          },
        });
      },
    }, {
      key: 'remind',
      type: 'primary',
      name: '发起提醒',
      requiredSelected: 0,
      hidden: true,
      cb: (selectedKeys) => {
        dispatch({
          type: `${domain}/goToRemind`,
          payload: {
            id: selectedKeys[0],
          },
        });
      },
    }, {
      key: 'export',
      type: 'primary',
      name: '导出对账明细',
      requiredSelected: 1,
      cb: (selectedKeys) => {
        handleExport(`${exportExcelURL}/account/detail/${selectedKeys[0]}`);
      },
    }],
  };

  const modalProps = {
    dispatch,
    loading,
    domain,
    record: suppId,
    visible: modalVisible,
    maskClosable: false,
    width: '30%',
    title: '选择公司',
    wrapClassName: 'vertical-center-modal',
    onOk(data) {
      dispatch({
        type: `${domain}/`,
        payload: data,
      });
    },
    onCancel() {
      dispatch({
        type: `${domain}/hideModal`,
      });
    },
  };

  return (
    <div className="content-inner">
      <DataTable {...tableProps} />
      {modalVisible && <ModalView {...modalProps} />}
    </div>
  );

};

export default connect(({ accounts, loading }) => ({
  accounts,
  loading,
}))(Accounts);
