import BaseInfo from './components/baseInfo';
import SkuInfo from './components/skuInfo';
import IntroduceInfo from './components/introduceInfo';
import './index.scss';
import { Button, message } from 'antd';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useEffect, useRef, useState } from 'react';
import { PilotTrainAPI } from '~/api';
import { InterDataType } from '~/api/interface';
import { listOrgPageType } from '~/api/interface/pilotTrainType';
//sku类型
type tableDataType = {
  gradeId: number;
  id: number;
  mainImage: string;
  modelsId: number;
  price: number;
  typeId: number;
  fileList: any[];
};
//机构列表返回类型
type institutionListType = InterDataType<listOrgPageType>['list'];

const AddOrEditInstitution = () => {
  const baseRef = useRef<any>();
  const skuRef = useRef<any>();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  //机构介绍
  const [introduceInfo, setIntroduceInfo] = useState<string>('');
  //机构id
  const [institutionId, setInstitutionId] = useState<number | undefined>(-1);
  //机构详情
  const [institutionDetail, setInstitutionDetail] = useState<institutionListType[0]>();

  const setIntroduceInfoEvent = (html: string) => {
    setIntroduceInfo(html);
  };
  //保存
  const saveDataClick = () => {
    Promise.all([
      baseRef.current.getForm().validateFields(),
      skuRef.current.getForm().validateFields(),
    ])
      .then((value) => {
        const skuReqData = skuRef.current.getTableData().map((v: tableDataType) => {
          return Object.getOwnPropertyNames(v).reduce((pre: any, cur: string) => {
            if (Object.getOwnPropertyNames(value[1]).includes(cur + v.id)) {
              pre[cur] = value[1][cur + v.id];
            }
            return pre;
          }, {});
        });
        PilotTrainAPI[institutionId ? 'updateOrg' : 'insertOrg']({
          ...value[0],
          trainingProgramsVOS: skuReqData,
          detail: introduceInfo,
          longitude: baseRef.current.getPosition().lon,
          latitude: baseRef.current.getPosition().lat,
          detailedAddress: baseRef.current.getPosition().address,
          id: institutionId || undefined,
        }).then(({ code }) => {
          if (code === '200') {
            message.success(institutionId ? '编辑机构成功' : '上传机构成功');
            navigate(-1);
          }
        });
      })
      .catch((error) => {
        message.warning(error.errorFields[0].errors[0]);
      });
  };
  //机构详情
  const getOrgPageDetail = (id: number) => {
    PilotTrainAPI.getListOrgPage({ pageNo: 1, pageSize: 10, id }).then(({ result }) => {
      if (result.list) {
        setInstitutionDetail({ ...result.list[0] });
      }
    });
  };
  //返回
  const backRoute = () => {
    navigate(-1);
  };
  useEffect(() => {
    if (searchParams.get('id')) {
      getOrgPageDetail(Number(searchParams.get('id')));
      setInstitutionId(Number(searchParams.get('id')));
    } else {
      setInstitutionId(undefined);
    }
  }, []);
  useEffect(() => {
    if (institutionDetail) {
      baseRef.current.getForm().setFieldsValue({
        mainImage: institutionDetail.mainImage,
        auxiliaryPicture: institutionDetail.auxiliaryPicture,
        video: institutionDetail.video,
        name: institutionDetail.name,
        region: institutionDetail.region,
        testCenter: institutionDetail.testCenter,
        scaleId: institutionDetail.scaleId || undefined,
        description: institutionDetail.description || undefined,
      });
      baseRef.current.getDefaultDataEvent().setPosition({
        lat: institutionDetail.latitude,
        lon: institutionDetail.longitude,
        address: institutionDetail.detailedAddress,
        adCode: institutionDetail.region.split(',')[1],
      });
      baseRef.current.getDefaultDataEvent().setMainImgList([
        {
          id: Math.random(),
          uid: Math.random(),
          url: institutionDetail.mainImage,
          name: 'mainImage',
        },
      ]);
      baseRef.current.getDefaultDataEvent().setSubImgList(
        institutionDetail.auxiliaryPicture.split(',').map((v: string) => ({
          id: Math.random(),
          uid: Math.random(),
          url: v,
          name: 'auxiliaryPicture',
        })),
      );
      baseRef.current.getDefaultDataEvent().setVideoList([
        {
          id: Math.random(),
          uid: Math.random(),
          url: institutionDetail.video,
          name: 'video',
        },
      ]);
      const programsList = institutionDetail.programsDOList.map((v) => ({
        ...v,
        fileList: [
          {
            id: Math.random(),
            uid: Math.random(),
            name: 'img',
            url: v.mainImage,
          },
        ],
      }));
      skuRef.current.setDefaultDataEvent().setDefaultTableData(programsList);
      const skuObj = institutionDetail.programsDOList.reduce((pre: any, cur: any) => {
        Object.getOwnPropertyNames(cur)
          .filter((key: string) => key !== 'id')
          .forEach((v: string) => {
            pre[v + cur.id] = cur[v];
          });
        return pre;
      }, {});
      skuRef.current.getForm().setFieldsValue(skuObj);
      setIntroduceInfo(institutionDetail.detail);
    }
  }, [institutionDetail]);
  return (
    <div className='institution-form'>
      <BaseInfo ref={baseRef} />
      <SkuInfo ref={skuRef} />
      <IntroduceInfo setIntroduceInfoEvent={setIntroduceInfoEvent} introduceInfo={introduceInfo} />
      <div className='institution-form-operate'>
        <Button type='primary' onClick={saveDataClick}>
          保存
        </Button>
        <Button onClick={backRoute}>返回</Button>
      </div>
    </div>
  );
};
export default AddOrEditInstitution;
