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) => {
        if (!introduceInfo) {
          return message.warning('机构介绍不能为空');
        }
        const skuReqData = skuRef.current.getTableData().reduce((list: any, v: tableDataType) => {
          const Obj = 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;
          }, {});
          if (
            Object.getOwnPropertyNames(Obj).length &&
            !Object.getOwnPropertyNames(Obj).every(
              (key: string) => Obj[key] === '' || Obj[key] === undefined || Obj[key] === null,
            )
          ) {
            list.push(Obj);
          }
          return list;
        }, []);
        PilotTrainAPI[institutionId ? 'updateOrg' : 'insertOrg']({
          ...value[0],
          region: [
            baseRef.current.getPosition().adCode.toString().substring(0, 2) + '0000',
            baseRef.current.getPosition().adCode.toString().substring(0, 4) + '00',
          ].join(','),
          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 || undefined,
        video: institutionDetail.video,
        name: institutionDetail.name,
        region: institutionDetail.detailedAddress,
        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().setIsEditAddress(true);
      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(
        institutionDetail.video
          ? [
              {
                id: Math.random(),
                uid: Math.random(),
                url: institutionDetail.video,
                name: 'video',
              },
            ]
          : [],
      );
      if (institutionDetail.programsDOList) {
        const programsList = institutionDetail.programsDOList.map((v) => ({
          ...v,
        }));
        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;
