import { Toolbar } from '@bizComponents';
import { DataTable, EditableDataTable, FormEL, SuggestSelect, UdcSelect } from '@components';
import { formUtils, enums } from '@utils';
import { Button, Card, DatePicker, Input, InputNumber, message, Tooltip, Modal } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import React from 'react';
import InvoiceModal from './invoiceModal';
import { numberUtils } from '@utils';

const { invoice, viewMode } = enums

const Detail = ({ formaInvoice,invoiceModal, dispatch, loading }) => {

  const { mode, formData, list, quotaList,itemVisible,handleBtn,filterParams } = formaInvoice;
  const {itemList,total, formInfo } = invoiceModal;
  const { confirm } = Modal;
  const domain = 'formaInvoice';
  const itemDomain='invoiceModal';
  let readOnly = false;
  let approval = false;
  let taxFlag = true;

  readOnly = (mode === viewMode.VIEW || mode === viewMode.APPROVAL) ? true : false;
  approval = mode === viewMode.APPROVAL ? true : false;
  taxFlag = mode !== viewMode.VIEW ? false : true;

  const itemProps = {
    dispatch,
    loading,
    domain:itemDomain,
    record: itemList,
    formInfo: formInfo,
    total,
    visible: itemVisible,
    maskClosable: false,
    width: '80%',
    confirmLoading: loading.effects[`${domain}/update`],
    title: '尾差处理',
    wrapClassName: 'vertical-center-modal',
    onCancel() {
      dispatch({
        type: `${domain}/hideModal`,
      });
      dispatch({
        type: `${domain}/queryView`,
        payload: filterParams
      });
    },
  };

  // 基本信息form
  const basic = [
    {
      title: '形式发票号',
      dataIndex: 'invNo',
    }, {
      title: '供应商编号',
      dataIndex: 'suppCode',
    }, {
      title: '供应商名称',
      dataIndex: 'suppName',
    }, {
      title: '企业编号',
      dataIndex: 'ouCode',
    }, {
      title: '企业名称',
      dataIndex: 'ouName',
    }, {
      title: '币种',
      dataIndex: 'currName',
    }, {
      title: '开票总金额(含税)',
      dataIndex: 'invAmtStr',
    }, {
      title: '开票总金额(未税)',
      dataIndex: 'netAmtStr',
    }, {
      title: '开票总税额',
      dataIndex: 'taxAmtStr',
    }, {
      title: '发票总金额(含税)',
      dataIndex: 'actInvAmtStr',
    }, {
      title: '发票总金额(未税)',
      dataIndex: 'actNetAmtStr',
    }, {
      title: '发票总税额',
      dataIndex: 'actTaxAmtStr',
    }, {
      title: '总金额差异(含税)',
      dataIndex: 'gapAmtStr',
    }, {
      title: '总金额差异(未税)',
      dataIndex: 'gapNetAmtStr',
    }, {
      title: '税额差异',
      dataIndex: 'gapTaxAmtStr',
    }];

  // 拆分发票
  const invSplit = [{
    title: '选择发票类型',
    dataIndex: 'invForm',
    tag: <UdcSelect domain="SRM" code="INV_FORM" allowClear={false} />,
    option: {
      initialValue: formData ? formData.invForm : '1',
      rules: [
        {
          required: true,
          message: '必填',
        },
      ],
    }
  }, {
    title: '定额',
    dataIndex: 'quotaCode',
    tag: <UdcSelect domain="SRM" code="INV_FIXAMT" allowClear={false} />,
    option: {
      initialValue: formData ? formData.quotaCode : '05',
      rules: [
        {
          required: true,
          message: '必填',
        },
      ],
    }
  }, {
    title: '发票张数',
    dataIndex: 'invNum',
  }];

  // 发票明细列表
  const columns = [{
    title: '发票形式',
    dataIndex: 'invType',
    width: 150,
    key: 'invType',
    required: true,
    render: (value, row, index) => {
      return (
        <UdcSelect domain="SRM" code="INV_FORM" value={row.invType} disabled={readOnly}
          onChange={(v) => {
            handleUpdateListProp(v, index, 'invType');
          }}
        />
      );
    }
  }, {
    title: '发票种类',
    dataIndex: 'invClass',
    className: 'alignRight',
    key: 'invClass',
    width: 200,
    required: true,
    render: (value, row, index) => {
      return (
        <UdcSelect disabled={readOnly} value={value} domain="SRM" code="INV_TYPE"
          onChange={(e) => handleUpdateListProp(e, index, 'invClass')}
        />
      );
    }
  }, {
    title: '发票代码',
    dataIndex: 'invNo',
    width: 150,
    key: 'invNo',
    required: true,
    render: (value, row, index) => {
      return (
        <Input
          value={value}
          disabled={readOnly}
          maxLength={12}
          placeholder="10或12位字符"
          onChange={(e) => {
            handleUpdateListProp(e.target.value, index, 'invNo');
          }}
        />
      );
    },
  }, {
    title: '发票号码',
    dataIndex: 'invIdCode',
    width: 150,
    key: 'invIdCode',
    required: true,
    render: (value, row, index) => {
      return (
        <Input
          value={value}
          disabled={readOnly}
          maxLength={8}
          placeholder="8位字符"
          onChange={(e) => {
            handleUpdateListProp(e.target.value, index, 'invIdCode');
          }}
        />
      );
    },
  }, {
    title: '发票校验码',
    dataIndex: 'invSymbol',
    width: 150,
    key: 'invSymbol',
    render: (value, row, index) => {
      return (
        <Input
          value={value}
          disabled={readOnly}
          maxLength={6}
          placeholder="校验码后六位"
          onChange={(e) => {
            handleUpdateListProp(e.target.value, index, 'invSymbol');
          }}
        />
      );
    },
  }, {
    title: '发票真伪',
    dataIndex: 'invStatusName',
    width: 100,
    key: 'invStatusName',

  }, {
    title: '开票日期',
    dataIndex: 'invDate',
    width: 150,
    key: 'invDate',
    required: true,
    render: (value, row, index) => {
      return (
        <DatePicker value={value ? moment(value) : value}
          format="YYYY-MM-DD"
          style={{ width: '100%' }}
          disabled={readOnly}
          onChange={(e) => {
            handleUpdateListProp(e, index, 'invDate');
          }}
        />
      );
    },
  }, {
    title: '税率(%)',
    dataIndex: 'taxRate',
    className: 'alignRight',
    key: 'taxRate',
    width: 200,
    required: true,
    render: (value, row, index) => {
      // console.log("value: ",value);
      return (
        <SuggestSelect apiName="invTax"
                       value={value}
                       // mode="multiple"
                       disabled={readOnly}
                       params={{ suppId: formData.suppId }}
                       onChange={(e) => handleUpdateListProp(e, index, 'taxRate')}
        />
      );
    }
  }, {
    title: '发票金额',
    dataIndex: 'invAmt',
    className: 'alignRight',
    key: 'invAmt',
    width: 150,
    render: (value) => {
      return (numberUtils.round_half_up_format(value, 2));
    },
  }, {
    title: '未税金额',
    dataIndex: 'netAmt',
    className: 'alignRight',
    key: 'netAmt',
    width: 150,
    required: true,
    render: (value, row, index) => {
      if (readOnly) {
        return (numberUtils.round_half_up_format(value, 2));
      } else {
        return (
          <InputNumber
            value={value}
            max={99999999}
            min={0}
            precision={2}
            style={{ width: '100%' }}
            disabled={readOnly}
            onChange={(e) => handleUpdateListProp(e, index, 'netAmt')}
          />);
      }
    },
  }, {
    title: '税额',
    dataIndex: 'taxAmt',
    className: 'alignRight',
    key: 'taxAmt',
    width: 150,
    required: true,
    render: (value, row, index) => {
      if (readOnly) {
        return (numberUtils.round_half_up_format(value, 2));
      } else {
        return (
          <InputNumber
            value={value}
            max={99999999}
            min={0}
            precision={2}
            style={{ width: '100%' }}
            disabled={readOnly}
            onChange={(e) => handleUpdateListProp(e, index, 'taxAmt')}
          />);
      }
    },
  }, {
    title: '备注',
    dataIndex: 'remark',
    className: 'alignLeft',
    key: 'remark',
    width: 200,
    render: (value) => {
      if (value) {
        return value.length > 5 ? <Tooltip placement="bottom" title={value}>
          {value && `${value.slice(0, 5)}...`}
        </Tooltip> : value;
      } else {
        return '无';
      }
    },
  }];

  const table = {
    domain,
    rowKey: 'id',
    scroll: {
      x: 2000,
      y: 400,
    },
    loading,
    dispatch,
    showAdd: !readOnly,
    showDelete: !readOnly,
    showCopy: false,
    enableSelection: !readOnly,
    // rowSelection,
    size: 'small',
  };

  const accountProps = {
    ...table,
    rowKey: 'randomId',
    scroll: {
      x: '100%',
      y: 400,
    },
    enablePagination: false,
    enableSelection: !handleBtn && mode==='approval',
    withFetch: false, // 表格不自动查询
    showAdd: false,
    showEdit: false,
    showView: false,
    showColumn: false,
    dataSource: formData ? formData.accountCheckDetailsList : [],
    columns: [{
      title: '物料编号',
      dataIndex: 'itemCode',
      width: '8%',
    }, {
      title: '物料名称',
      dataIndex: 'itemName',
      width: '12%',
    }, {
      title: '数量',
      dataIndex: 'qty',
      width: '6%',
      className: 'alignRight',
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value, 2)
        );
      }
    }, {
      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: 'taxRate',
      width: '6%',
    },
    {
      title: '总税额',
      dataIndex: 'taxAmt',
      width: '6%',
      className: 'alignRight',
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value, 2)
        );
      }
    },
    {
      title: '实际数量',
      dataIndex: 'deliQty',
      width: '8%',
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value, 2)
        );
      }
    },
    {
      title: '实际总价',
      dataIndex: 'deliAmt',
      width: '6%',
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value, 2)
        );
      },
    },
    ],
    buttons: [{
      key: 'view',
      type: 'primary',
      name: '尾差处理',
      requiredSelected: 1,
      cb: (selectedRowKeys, searchBarForm, selectedRows) => {
        dispatch({
          type: `${domain}/showModal`,
          payload: {
            ...selectedRows[0],
          },
        });
      },
    }],
  };

  // 进行发票校验
  // 只有正式发票需要进行校验
  // 1.当前开票，不允许出现 代码+号码+税率 均相同的发票
  // 2.当前开票，不允许出现 代码+号码 与历史发票相同的发票
  const finalConfirm = (submit) => {
    dispatch({
      type: `${domain}/checkInv`,
      payload: {
        submit: submit
      },
    });
  };

  const handleSave = () => {
    const newList = list ? list.filter(i => i.invType === '1') : [];
    if (newList.length && formUtils.checkEmptyField(newList, columns) === true) {
      message.error(invoice.ALL_REQUIRED, 3);
      return 0;
    }

    formUtils.validateForm(invSplit, formData, () => {
      // dispatch({ type: `${domain}/save` });
      finalConfirm(false);
    });

  };

  const handleSubmit = () => {
    let flag = 0;
    if (!formData.id) {
      return message.error(invoice.SAVED_THEN_SUBMIT, 3);
    }
    if (!list || (list && list.length <= 0)) {
      return message.error(invoice.SPLITED_THEN_SUBMIT, 3);
    } else if (formUtils.checkEmptyField(list, columns) === true) {
      return message.error(invoice.ALL_REQUIRED, 3);
    }

    list.map((i) => {
      if (i.invType !== '1') {
        message.error(invoice.INV_TYPE_ERR, 3);
        flag += 1;
        return false;
      }
      if (+i.taxAmt < 0) {
        message.error(invoice.TAX_AMT_ERR, 3);
        flag += 1;
        return false;
      }
      // 非专票时，发票校验码是必填
      if (i.invClass !== '01' && !i.invSymbol) {
        message.error(invoice.INV_SYMBOL_REQUIRED, 3);
        flag += 1;
        return false;
      } else if (i.invClass !== '01' && i.invSymbol && i.invSymbol.length !== 6) {
        message.error(invoice.INV_SYMBOL_ERR, 3);
        flag += 1;
        return false;
      }

      if (i.invNo && i.invNo.length !== 10 && i.invNo.length !== 12) {
        message.error(invoice.INV_NO_ERR, 3);
        flag += 1;
        return false;
      }
      if (i.invIdCode && i.invIdCode.length !== 8) {
        message.error(invoice.INV_ID_CODE_ERR, 3);
        flag += 1;
        return false;
      }

      i.invDate = moment(i.invDate).format('YYYY-MM-DD');
      if (i.invDate > moment().subtract(1, 'days').format('YYYY-MM-DD')) {
        message.error(invoice.INV_DATE_ERR, 3);
        flag += 1;
        return false;
      }

    });
    if (flag > 0) {
      return false;
    }
    formUtils.validateForm(invSplit, formData, () => {
      // dispatch({ type: `${domain}/submit` });
      finalConfirm(true);
    });
  };

  // 同意
  const handleApprove = () => {
    dispatch({ type: `${domain}/approve` });
  };

  // 拒绝
  const handleReject = () => {
    dispatch({ type: `${domain}/reject` });
  };

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

  const handleCancel = () => {
    dispatch({ type: `${domain}/cancel` });
  };

  const handleUpdateForm = (changedValues) => {

    dispatch({
      type: `${domain}/updateForm`, payload: {
        key: Object.keys(changedValues)[0],
        value: Object.values(changedValues)[0]
      }
    });
    if (Object.keys(changedValues)[0] === 'quotaCode') {
      const newQuota = quotaList.filter(item => item.code === Object.values(changedValues)[0]);
      dispatch({
        type: `${domain}/updateForm`, payload: {
          key: 'quota',
          value: +newQuota[0].valSphd1,
        }
      });
    }

  };

  const handleSplitInvoices = () => {
    dispatch({ type: `${domain}/split` });
  };
  const handleUpdateListProp = (value, index, key) => {
    // console.warn(value, index, key)
    dispatch({
      type: `${domain}/updateListProp`,
      payload: { value, index, key }
    });
  };

  const button = [{
    id: 'save',
    text: '保存',
    type: 'primary',
    onClick: () => {
      handleSave();
    },
  }, {
    id: 'submit',
    text: '提交',
    type: 'primary',
    onClick: () => {
      handleSubmit();
    },
  }];
  const apprButton = [{
    id: 'advice',
    placeholder: '请输入审批意见',
    onChange: (e) => {
      handleAdviceChange(e.target.value);
    }
  }, {
    id: 'approval',
    text: '同意',
    type: 'primary',
    onClick: () => {
      handleApprove();
    },
  }, {
    id: 'rejected',
    text: '拒绝',
    type: 'primary',
    onClick: () => {
      handleReject();
    },
  }];

  return (
    <div
      style={{ height: '100%' }}
    >
      {formData &&
        <Toolbar loading={loading} readOnly={readOnly} mode={mode} record={formData}
          buttons={!readOnly ? button : (approval ? apprButton : [])}
          handleSave={handleSave}
          handleCancel={handleCancel}
          defId={formData.defId}
          prcId={formData.prcId}
        />
      }

      < Card title="基本信息" id="basic" loading={loading.effects[`${domain}/query`]}>
        {formData &&
          <FormEL items={basic} record={formData} readOnly={readOnly}
            onFieldsChange={(changedValues) => handleUpdateForm(changedValues)} />
        }
      </Card>
      {!readOnly &&
        <Card
          title={<div>发票明细 <Button key="save" type="primary" onClick={() => handleSplitInvoices()}>拆分发票</Button></div>}
          id="detail"
          loading={loading.effects[`${domain}/query`]}
        >
          {formData &&
            <FormEL items={invSplit} record={formData} readOnly={readOnly}
              onFieldsChange={(changedValues) => handleUpdateForm(changedValues)}
            />
          }
        </Card>
      }

      <Card title="发票明细列表" id="makeInvoce" loading={loading.effects[`${domain}/query`]}>
        <EditableDataTable columns={columns} loading={loading} dataSource={list} dispatch={dispatch} {...table} />
      </Card>

      <Card title="对账明细" id="accountCheck" loading={loading.effects[`${domain}/query`]}>
        <DataTable {...accountProps} />
        {itemVisible && <InvoiceModal {...itemProps} />}
      </Card>
    </div>
  );
};

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