
import React from 'react';
import { Form } from 'kts-components-antd-x3';
import { Select, Input, Spin, InputProps, Cascader } from 'kts-xui';
import { WrappedFormUtils } from 'kts-components-antd-x3/lib/form/Form';
import { IGood2 } from '../../../../../InvoiceController';
import Invoice from '../../../../..';
import TitleText from './ui/TitleText';

export default (form: WrappedFormUtils) => {
  const { getFieldDecorator } = form;

  const controller = Invoice.useInvoiceController();

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

  /** 组件模式 */
  const model = controller.useMemo(e => e.model, []);

  /** 正在编辑的货物 */
  const editGood = controller.useMemo((e) => e.freightListState.editGood, []);

  /** 禁用字段 */
  const disableds = controller.useMemo((e) => e.stakeholder.disableds || [], []);

  /** 运输工具种类列表 */
  const vehicleTypeList = controller.useMemo((e) => e.freightListState.vehicleTypeList, []);

  const area = controller.useMemo((e) => e.freightListState.area, []);
  const addressFieldNames = controller.useMemo((e) => e.freightListState.addressFieldNames, []);
  const getVehicle = React.useCallback((value?: string) => {
    if (vehicleTypeList && vehicleTypeList.length > 0) {
      return vehicleTypeList.find(e => e.value === value)?.label || '';
    }
  }, [vehicleTypeList])
  const splitArea = React.useCallback((value?: string) => {
    if (value) {
      const _array = value.split(',');
      return _array;
    } else {
      return [];
    }
  }, []);

  /** 表头 */
  const columns = React.useMemo(() => {
    return [
      {
        title: '序号',
        key: 'sortNumber',
        dataIndex: 'sortNumber',
        width: 50,
        render: (e: number) => <span style={{ padding: '0 10px' }}>{e}</span>,
      },
      {
        title: <TitleText required >运输工具种类</TitleText>,
        key: 'type',
        render: (_: string, record: IGood2) => {
          if (editGood?.$index === record.$index && !disableds.includes('type') && !(model === 'prefab')) {
            return (
              <Form.Item>
                {getFieldDecorator('type', {
                  initialValue: editGood.type,
                  rules: [
                    { required: true, message: '请输入' },
                  ],
                })(
                  <Select
                    className="kts-invoice-operate-goods-list-table-tax-rate"
                    showArrow={false}
                    style={{ width: '100%' }}
                    getPopupContainer={() => rootElement || document.body}
                    onChange={async (value) => {
                      await controller.wait()
                      controller.setEditFreight({ type: value });
                    }}
                  >
                    {(record.vehicleList || vehicleTypeList).map((e, i) => {
                      return (
                        <Select.Option key={i} value={e.value}>
                          {e.label}
                        </Select.Option>
                      );
                    })}
                  </Select>,
                )}
              </Form.Item>
            );
          } else {
            return <span style={{ padding: '0 10px' }}>{getVehicle(record.type)}</span>;
          }
        },
      },
      {
        title: <TitleText required>运输工具牌号</TitleText>,
        key: 'licensePlate',
        width: 119,
        render: (_: string, record: IGood2) => {
          if (editGood?.$index === record.$index && !disableds.includes('licensePlate') && model !== 'prefab') {
            return (
              <Form.Item>
                {getFieldDecorator('licensePlate', {
                  initialValue: editGood.licensePlate,
                  rules: [
                    { required: true, message: '请输入' },
                  ],
                })(
                  <MyInput
                    maxLength={200}
                    onChange={async () => {
                      await controller.wait()
                      await controller.setEditFreight({ licensePlate: form.getFieldsValue().licensePlate });
                    }}
                  />,
                )}
              </Form.Item>
            );
          } else {
            return <span style={{ padding: '0 10px' }}>{record.licensePlate}</span>;
          }
        },
      },
      {
        title: <TitleText required>起运地</TitleText>,
        key: 'origin',
        width: 150,
        render: (_: string, record: IGood2) => {
          if (editGood?.$index === record.$index && !disableds.includes('origin') && model !== 'prefab') {
            return (
              <Form.Item>
                {getFieldDecorator('origin', {
                  initialValue: editGood.origin,
                  rules: [
                    { required: true, message: '请输入' },
                  ],
                })(<Cascader
                    style={{ width: '100%' }}
                    options={area}
                    fieldNames={addressFieldNames}
                    onChange={async (value) => {
                      await controller.setEditFreight({ origin: value });
                    }}
                  />)}
              </Form.Item>
            );
          } else {
            return <span style={{ padding: '0 10px' }}>{record.origin}</span>;
          }
        },
      },
      {
        title: <TitleText required>到达地</TitleText>,
        dataIndex: 'destination',
        key: 'destination',
        width: 149,
        render: (_: string, record: IGood2) => {
          if (editGood?.$index === record.$index && !disableds.includes('destination') && model !== 'prefab') {
            return (
              <Form.Item>
                {getFieldDecorator('destination', {
                  initialValue: editGood.destination,
                  rules: [
                    { required: true, message: '请输入' },
                  ],
                })(
                  <Cascader
                    options={area}
                    fieldNames={addressFieldNames}
                    style={{ width: '100%' }}
                    onChange={async (value) => {
                      await controller.setEditFreight({ destination: value });
                    }}
                  />
                )}
              </Form.Item>
            );
          } else {
            return <span style={{ padding: '0 10px' }}>{record.destination}</span>;
          }
        },
      },
      {
        title: <TitleText required>运输货物名称</TitleText>,
        dataIndex: 'itemName',
        key: 'itemName',
        width: 149,
        render: (_: string, record: IGood2) => {
          if (editGood?.$index === record.$index && !disableds.includes('itemName') && model !== 'prefab') {
            return (
              <Form.Item>
                {getFieldDecorator('itemName', {
                  initialValue: editGood.itemName,
                  rules: [
                    { required: true, message: '请输入货物名称' },
                  ],
                })(
                  <MyInput
                    maxLength={200}
                    onChange={async () => {
                      await controller.wait()
                      await controller.setEditFreight({ itemName: form.getFieldsValue().itemName });
                    }}
                  />,
                )}
              </Form.Item>
            );
          } else {
            return <span style={{ padding: '0 10px' }}>{record.itemName}</span>;
          }
        },
      },
    ]

      // 只读
      .filter(e => {
        if (model === 'readOnly') {
          return e.key !== 'operating';
        } else {
          return true;
        }
      })
      .map((e) => {
        return {
          ...e,
          ellipsis: true,
        };
      }) as any[];
  }, [editGood, controller, model, getVehicle]);

  return columns;
};


class MyInput extends React.Component<InputProps & { loading?: boolean }> {
  render() {
    if (this.props.loading) {
      return (
        <Spin size="small">
          <Input {...this.props} autoComplete="off" />
        </Spin>
      )
    } else {
      return <Input {...this.props} autoComplete="off" />
    }
  }
}
