import React from 'react';
import { Row, Col, Input, Tag, Icon, Form, Select } from 'kts-components-antd-x3';
import { decorator } from 'grey-react-box';
import { FormComponentProps } from 'kts-components-antd-x3/lib/form';
// import moment from 'moment';
import { ReactComponent as AutoSvg } from './auto.svg';
import Invoice from '../../..';
import './index.less';
import { WrappedFormUtils } from 'kts-components-antd-x3/lib/form/Form';

export interface IInvoiceHeader {
  /** 标题 */
  title?: string;

  /** 标记文字 */
  tag?: string;

  /** 是否显示发票单据编号 */
  isInvoiceNo?: boolean;

  /** 是只读 发票单据编号 */
  readOnlyInvoiceNo?: boolean;

  /** 默认 编号 */
  defaultId?: string;

  /** 默认 发票代码 */
  defaultCode?: string;

  /** 默认 发票号码 */
  defaultNo?: string;

  /** 效验码 */
  defaultValidationCode?: string;

  /** 默认 开票日期 */
  defaultInvoicingDate?: string;

  /** 字段扩展 */
  fieldExpand?: { label: React.ReactNode, render: (form: WrappedFormUtils<any>) => React.ReactChild }[];

  /** 发票类型 索引 */
  typeOptionIndex?: number;

  /** 发票类型 */
  typeOption?: { title: string, value: any }[];

  /** 发票类型 被切换 */
  onChangeTypeOption?: (e: number) => void;

  /** 渲染扩展 */
  renderExpand?: (form: WrappedFormUtils<any>) => React.ReactChild;
}

export default decorator<IInvoiceHeader, IInvoiceHeader & FormComponentProps>(Form.create())((props) => {

  const { tag, isInvoiceNo = true, form } = props;

  const { getFieldDecorator, setFieldsValue } = form;

  const [typeIndex, setTypeIndex] = React.useState(props.typeOptionIndex || 0);

  /** 控制器 */
  const controller = Invoice.useInvoiceController();

  const model = controller.useMemo(s => s.model, []);

  /** 是只读 发票单据编号 */
  const readOnlyInvoiceNo = React.useMemo(() => {
    if (model === 'prefab') return true;
    return props.readOnlyInvoiceNo || false;
  }, [props.readOnlyInvoiceNo, model])

  controller.useForm('invoiceHeader', form);

  const title = React.useMemo(() => {
    if (props.typeOption && props.typeOption[typeIndex]) {
      return props.typeOption[typeIndex].title
    }
    if (props.title) {
      return props.title
    }
    return '增值税电子专用发票'
  }, [props.typeOption, props.title, typeIndex])

  const fieldExpand = React.useMemo(() => {
    const fieldExpand = []

    if (!props.fieldExpand || props.fieldExpand.some(e => `${e.label}`.replace(" :", '') === '发票代码') === false) {
      fieldExpand.push({
        label: '发票代码 :',
        render: (form: WrappedFormUtils<any>) => form.getFieldDecorator('code', {
          initialValue: props.defaultCode,
        })(<FormSpanString />)
      })
    }

    if (!props.fieldExpand || props.fieldExpand.some(e => `${e.label}`.replace(" :", '') === '发票号码') === false) {
      fieldExpand.push({
        label: '发票号码 :',
        render: (form: WrappedFormUtils<any>) => form.getFieldDecorator('no', {
          initialValue: props.defaultNo,
        })(<FormSpanString />)
      })
    }

    if (props.defaultInvoicingDate) {
      fieldExpand.push({
        label: '开票日期 :',
        render: (form: WrappedFormUtils<any>) => form.getFieldDecorator('invoicingDate', {
          initialValue: props.defaultInvoicingDate,
        })(<FormSpanString />)
      })
    }

    if (props.defaultValidationCode) {
      fieldExpand.push({
        label: '校验码 :',
        render: (form: WrappedFormUtils<any>) => form.getFieldDecorator('defaultValidationCode', {
          initialValue: props.defaultValidationCode,
        })(<FormSpanString />)
      })
    }

    return [...fieldExpand, ...props.fieldExpand || []];
  }, [props.fieldExpand, props.defaultValidationCode])

  // 发票类型 索引 props 变化
  React.useEffect(() => {
    setTypeIndex(props.typeOptionIndex || 0);
  }, [props.typeOptionIndex])

  // 组件内部 改变了 发票类型 索引
  React.useEffect(() => {
    if (typeIndex === props.typeOptionIndex) return;
    if (!props.onChangeTypeOption) return;
    props.onChangeTypeOption(typeIndex);
  }, [typeIndex, props.onChangeTypeOption, props.typeOptionIndex])

  React.useEffect(() => {
    setTypeIndex(props.typeOptionIndex || 0);
  }, [props.typeOption])

  return (
    <div className="kts-invoice-operate-invoice-header">
      <div className="invoice-header-title">{title}</div>
      <div className="invoice-header-no">
        {isInvoiceNo
          ? <div>
            <label>发票单据编号 :</label>
            {getFieldDecorator('id', {
              initialValue: props.defaultId,
            })(
              <Input
                disabled={readOnlyInvoiceNo}
                style={{ width: 230 }}
                size="small"
                suffix={
                  controller.updateInvoiceNo &&
                  <Icon
                    style={{ cursor: 'pointer' }}
                    component={AutoSvg}
                    onClick={async () => {
                      controller.updateInvoiceNo &&
                        setFieldsValue({ id: await controller.updateInvoiceNo() });
                    }}
                  />
                }
              />
            )}
          </div>
          : <div style={{ height: 20 }}></div>}
        {tag && <Tag>{tag}</Tag>}
        <div className="invoice-header-type">
          {props.typeOption
            ? getFieldDecorator('type', {
              initialValue: typeIndex
            })(
              <Select
                size="small"
                style={{ width: 230 }}
                onChange={e => { setTypeIndex(e as number); }}
              >
                {props.typeOption.map((e, i) => {
                  return <Select.Option key={i} value={i}>{e.title}</Select.Option>
                })}
              </Select>
            )
            : props.renderExpand && props.renderExpand(props.form)}
        </div>
      </div>
      {
        props.typeOption && (
          <div style={{ marginTop: 10 }} >
            {props.renderExpand && props.renderExpand(props.form)}
          </div>
        )
      }
      <div className="invoice-header-property">
        {
          [...props.fieldExpand || []].map(e => {
          })
        }
        {/* <Row>
          {
            fieldExpand.map(e => {
              return (
                <Col span={parseInt(`${24 / fieldExpand.length}`)}>
                  <label>{e.label}</label>
                  {e.render(form)}
                </Col>
              )
            })
          }
        </Row> */}
        <ul className='invoice-header-property-fieldExpand' >
          {
            fieldExpand.map(e => {
              return (
                <li>
                  <label>{e.label}</label>
                  {e.render(form)}
                </li>
              )
            })
          }
        </ul>
      </div>
    </div>
  );
});

class FormSpanString extends React.Component<{ value?: any }> {
  render() {
    // return <span>{this.props.value}</span>;
    return <Input size="small" disabled value={this.props.value} />
  }
}

// class FormSpanMoment extends React.Component<{ value?: any }> {
//   render() {
//     if(!this.props.value) return <></>
//     if(!this.props.value.format) return <></>
//     return <span>{this.props.value?.format('YYYY-MM-DD HH:mm') ?? ''}</span>;
//   }
// }
