import './index.scss';
import { Button, Col, Form, Row, Table } from 'antd';
import { MinusOutlined, PlusOutlined } from '@ant-design/icons';
import EditableCell from '~/components/EditableCell';
import React, { FC, forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import { PilotTrainAPI } from '~/api';
import { InterDataType } from '~/api/interface';
import {
  licenceGradeListType,
  licenceModelsListType,
  licenceTypeListType,
} from '~/api/interface/pilotTrainType';
type EditableTableProps = Parameters<typeof Table>[0];
type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;
type tableDataType = {
  gradeId: number;
  id: number;
  mainImage: string;
  modelsId: number;
  price: number;
  typeId: number;
  fileList: any[];
};
//机型下拉返回类型
type modelsListType = InterDataType<licenceModelsListType>;
//等级下拉返回类型
type gradeListType = InterDataType<licenceGradeListType>;
//执照类型返回类型
type typeListType = InterDataType<licenceTypeListType>;

interface selfProps {
  ref: any;
}

const SkuInfo: FC<selfProps> = forwardRef((props, ref) => {
  const [skuForm] = Form.useForm<any>();
  //机型下拉列表
  const [modelsList, setModelsList] = useState<modelsListType>([]);
  //等级下拉列表
  const [gradeList, setGradeList] = useState<gradeListType>([]);
  //执照类型列表
  const [typeList, setTypeList] = useState<typeListType>([]);

  //价格正则
  const priceValidator = (_rule: any, value: any) => {
    const reg = /^\d+(\.\d{1,2})?$/;
    if (reg.test(value)) {
      if (value < 0 || value > 100000) {
        return Promise.reject(new Error('价格大于0且小于10万'));
      }
    } else {
      return Promise.reject(new Error('价格为数字且保留小数点后两位'));
    }
    return Promise.resolve();
  };

  const defaultColumns: (ColumnTypes[number] & {
    editable?: boolean;
    dataIndex?: string;
    selectOption?: { name: string; id: number }[];
    inputType?: string;
    rules?: any;
  })[] = [
    {
      title: '序号',
      align: 'center',
      render: (_text: string, _record, index: number) => index + 1,
      width: '10%',
    },
    {
      title: '培训主图',
      align: 'center',
      dataIndex: 'mainImage',
      width: '10%',
      inputType: 'uploader',
      editable: true,
      rules: [{ required: 'true', message: '请上传培训主图' }],
    },
    {
      title: '培训机型',
      align: 'center',
      editable: true,
      dataIndex: 'modelsId',
      inputType: 'select',
      width: '15%',
      selectOption: modelsList,
      rules: [{ required: 'true', message: '请选择培训机型' }],
    },
    {
      title: '培训等级',
      align: 'center',
      editable: true,
      dataIndex: 'gradeId',
      inputType: 'select',
      width: '15%',
      selectOption: gradeList,
      rules: [{ required: 'true', message: '请选择培训等级' }],
    },
    {
      title: '培训类型',
      align: 'center',
      editable: true,
      dataIndex: 'typeId',
      inputType: 'select',
      width: '15%',
      selectOption: typeList,
      rules: [{ required: 'true', message: '请选择培训类型' }],
    },
    {
      title: '培训价格',
      align: 'center',
      editable: true,
      dataIndex: 'price',
      width: '12%',
      rules: [{ required: 'true', validator: priceValidator }],
    },
    {
      title: '操作',
      width: '10%',
      onHeaderCell: () => {
        return {
          style: {
            textAlign: 'center',
          },
        };
      },
      render: (_text: string, record: any, index) => (
        <>
          {index === tableData.length - 1 ? (
            <Button
              icon={<PlusOutlined />}
              type='primary'
              onClick={addTrainSku}
              style={{ marginRight: '10px' }}
            ></Button>
          ) : (
            ''
          )}

          {index ? (
            <Button icon={<MinusOutlined />} danger onClick={() => deleteTrainSku(record)}></Button>
          ) : (
            ''
          )}
        </>
      ),
    },
  ];
  const columns = defaultColumns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: any) => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        editing: true,
        selectOption: col.selectOption,
        inputType: col.inputType,
        uploadSuccess: col.inputType === 'uploader' ? uploadSuccess : undefined,
        rules: col.rules,
      }),
    };
  });
  const [tableData, setTableData] = useState<tableDataType[]>([
    {
      id: Math.random(),
      gradeId: -1,
      mainImage: '',
      modelsId: -1,
      price: -1,
      typeId: -1,
      fileList: [],
    },
  ]);
  useImperativeHandle(ref, () => ({
    getForm: () => skuForm,
    getTableData: () => tableData,
    setDefaultDataEvent: () => ({
      setDefaultTableData: (value: any) => setTableData(value),
    }),
  }));

  //加一条培训项目
  const addTrainSku = () => {
    setTableData([
      ...tableData,
      {
        id: Math.random(),
        gradeId: -1,
        mainImage: '',
        modelsId: -1,
        price: -1,
        typeId: -1,
        fileList: [],
      },
    ]);
  };
  //删除一条培训项目
  const deleteTrainSku = (record: tableDataType) => {
    const index: number = tableData.findIndex((v) => v.id === record.id);
    tableData.splice(index, 1);
    setTableData([...tableData]);
  };
  //主图上传
  const uploadSuccess = (record: tableDataType, result: any) => {
    const index: number = tableData.findIndex((v) => v.id === record.id);
    skuForm.setFieldValue('mainImage' + record.id, result[0].url);
    tableData[index].mainImage = result[0].url;
    tableData[index].fileList = result;
    setTableData([...tableData]);
  };
  //培训机型下拉
  const getLicenceModelsList = () => {
    PilotTrainAPI.getLicenceModelsList().then(({ result }) => {
      setModelsList(result || []);
    });
  };
  //培训等级下拉
  const getLicenceGradeList = () => {
    PilotTrainAPI.getLicenceGradeList().then(({ result }) => {
      setGradeList(result || []);
    });
  };
  //培训类型下拉
  const getLicenceTypeList = () => {
    PilotTrainAPI.getLicenceTypeList().then(({ result }) => {
      setTypeList(result || []);
    });
  };

  useEffect(() => {
    getLicenceModelsList();
    getLicenceGradeList();
    getLicenceTypeList();
  }, []);
  return (
    <div className='sku-info'>
      <div className='sku-info-header'>培训项目：</div>
      <div className='sku-info-table'>
        <Row>
          <Col span={1}></Col>
          <Col span={18}>
            <Form form={skuForm} component={false}>
              <Table
                size='small'
                rowKey='id'
                bordered
                columns={columns as ColumnTypes}
                components={{
                  body: {
                    cell: EditableCell,
                  },
                }}
                dataSource={tableData}
                pagination={false}
              />
            </Form>
          </Col>
        </Row>
      </div>
    </div>
  );
});
export default SkuInfo;
