import { Select, Space, message } from 'antd';
import { useRouter } from 'next/router';
import { useContext, useEffect, useState } from 'react';
import ContentBox from '~/components/contentBox';
import Map from './components/map';
import RotationChart from './components/rotationChart';
import { Box } from './styled';

import { UserContext } from '~/lib/userProvider';
import api, {
  AllType,
  NewsPageType,
  NewsTenderType,
  equipmentLeasingApi,
  flightSkillsApi,
  jobServicesApi,
  listNewsApi,
  mallApi,
} from './api';
import { bigNumberTransform } from '~/utils/money';

interface ColumnsType {
  title: string;
  router: string;
}

export default function WaterfallFlowBody() {
  const router = useRouter();
  const { userInfo, setNeedLogin } = useContext(UserContext);

  const [list, setList] = useState([
    '中国人寿',
    '中国平安',
    '中国人保',
    '太平洋保险',
    '新华保险',
    '中国太平',
    '泰康保险',
    '华夏保险',
    '阳光保险',
    '富德生命人寿',
    '中邮人寿',
    '前海人寿',
    '百年人寿',
    '国华人寿',
    '工银安盛人寿',
    '恒大人寿',
    '君康人寿',
    '友邦保险',
    '建信人寿',
    '大家人寿',
    '农银人寿',
    '中信保城人寿',
    '合众人寿',
  ]);
  const [list2, setList2] = useState([
    '天目将PAAS平台',
    '天目将公安平台',
    '天目将应急平台',
    '天目将城管平台',
    '天目将电力平台',
    '天目将石油平台',
    'SESP-U1无人机仿真软件',
    '云享飞服务号',
    '无人机商城',
    '云飞手',
    '云仓',
    '云享飞',
    '科比特智教',
  ]);

  const columns = [
    {
      title: '无人机出租',
      router: '/equipmentLeasing',
    },
    {
      title: '无人机销售',
      router: '/mall',
    },
    {
      title: '无人机保险',
      router: '',
    },
    {
      title: '无人机培训',
      router: 'flyingHandService',
    },
    {
      title: '无人机服务',
      router: '/jobServices',
    },
    {
      title: '无人机工具软件',
      router: '',
    },
  ];

  const [leftDomList, setLeftDomList] = useState(Array<{ element: JSX.Element; type?: string }>);

  const [rightTopDomList, setRightTopDomList] = useState<JSX.Element>();
  const [rightBottomDomList, setRightBottomDomList] = useState<JSX.Element>();

  // const { deviceBrand, deviceModel } = equipmentLeasingApi
  // const eqApiTypeList = ['brandId', 'categoryId', 'modelId']

  // const {
  //   listAllModel,
  //   listAllBrand,
  //   listAllCategory,
  //   listAllParts,
  //   listAllQuality,
  // } = mallApi
  // const mallApiTypeList = [
  //   'brandId',
  //   'productCategoryId',
  //   'partsId',
  //   'modelId',
  //   'qualityId',
  // ]
  // const { IndustryFlightSkills, InDronePilotLicense } = flightSkillsApi
  // const flightApiTypeList = ['licenseId', 'flightSkillsId']

  // const { listAllIndustry, listAllAppType } = jobServicesApi
  // const jobApiTypeList = ['industryId', 'appTypeId']

  const onMoreChange = (value: { value: string; label: number }, index: number, option: []) => {
    const [item] = option.filter((item: any) => item.name === value.value);
    routerPath(index, item);
  };

  // useEffect(() => {
  //   ;(async () => {
  //     let res1 = await Promise.all([deviceBrand(), deviceModel()])
  //     let res2 = await Promise.all([listAllBrand(), listAllCategory(), listAllParts(), listAllModel(), listAllQuality()])
  //     let res3 = await Promise.all([IndustryFlightSkills(), InDronePilotLicense()])
  //     let res4 = await Promise.all([listAllIndustry(), listAllAppType()])
  //     //  let res4 = await Promise.all([deviceCategory(),deviceBrand(),deviceModel()])
  //     //  let res6 = await Promise.all([deviceCategory(),deviceBrand(),deviceModel()])

  //     const resValuelist1 = res1
  //       .map((item, index) => {
  //         if (item.code === '200') {
  //           return item.result?.map(it => {
  //             it.type = eqApiTypeList[index]
  //             return it
  //           })
  //         }
  //         return {}
  //       })
  //       .flat()

  //     const resValuelist2 = res2
  //       .map((item, index) => {
  //         if (item.code === '200') {
  //           return item.result?.map(it => {
  //             it.type = mallApiTypeList[index]
  //             return it
  //           })
  //         }
  //         return {}
  //       })
  //       .flat()
  //     const resValuelist3 = res3
  //       .map((item, index) => {
  //         if (item.code === '200') {
  //           return item.result?.map(it => {
  //             it.type = flightApiTypeList[index]
  //             it.name = it.name || it.skillsName || it.licenseType
  //             return it
  //           })
  //         }
  //         return {}
  //       })
  //       .flat()
  //     const resValuelist4 = res4
  //       .map((item, index) => {
  //         if (item.code === '200') {
  //           return item.result?.map(it => {
  //             it.type = jobApiTypeList[index]
  //             it.name = it.name || it.appName
  //             return it
  //           })
  //         }
  //         return {}
  //       })
  //       .flat()

  //     let res7 = await listNewsApi.listNewsPage({ pageNo: 1, pageSize: 5 })
  //     let res8 = await listNewsApi.listNewTenderInfo({
  //       pageNo: 1,
  //       pageSize: 6
  //     })
  //     const listValue: any = [resValuelist1, resValuelist2, [], resValuelist3, resValuelist4, []]
  //     const listOption = JSON.parse(JSON.stringify(list)).map((item: string, index: number) => {
  //       return { id: index, name: item, value: index }
  //     })
  //     const list2Option = JSON.parse(JSON.stringify(list2)).map((item: string, index: number) => {
  //       return { id: index, name: item, value: index }
  //     })

  //     const optionList = [resValuelist1, resValuelist2, listOption, resValuelist3, resValuelist4, list2Option]

  //     setLeftDomList(
  //       columns.map((item, index) => {
  //         if (index < 3) {
  //           return {
  //             element: leftDom(item, index, listValue, optionList[index]),
  //             type: 'left'
  //           }
  //         }
  //         return {
  //           element: leftDom(item, index, listValue, optionList[index]),
  //           type: 'right'
  //         }
  //       })
  //     )

  //     setRightTopDomList(rightDom(res7.result?.list!))
  //     setRightBottomDomList(rightDom2(res8.result?.list!))
  //   })()
  // }, [])

  useEffect(() => {
    (async () => {
      const res2 = await api.HomeCategories({ type: 2 }); //无人机培训
      const res4 = await api.HomeCategories({ type: 4 }); //无人机销售
      const res1 = await api.HomeCategories({ type: 1 }); //无人机出租
      const res3 = await api.HomeCategories({ type: 3 }); //无人机服务
      console.log(res1, res2, res3, res4);
      const listOption = JSON.parse(JSON.stringify(list)).map((item: string, index: number) => {
        return { id: index, categoryName: item, value: index };
      });
      const list2Option = JSON.parse(JSON.stringify(list2)).map((item: string, index: number) => {
        return { id: index, categoryName: item, value: index };
      });
      const optionList = [
        res2.result,
        res4.result,
        listOption,
        res3.result,
        res1.result,
        list2Option,
      ];
      const listValue: any = [res2.result, res4.result, [], res3.result, res1.result, []];
      setLeftDomList(
        columns.map((item, index) => {
          if (index < 3) {
            return {
              element: leftDom(item, index, listValue, optionList[index]),
              type: 'left',
            };
          }
          return {
            element: leftDom(item, index, listValue, optionList[index]),
            type: 'right',
          };
        }),
      );
      let res7 = await listNewsApi.listNewsPage({ pageNo: 1, pageSize: 5 });
      let res8 = await listNewsApi.listNewTenderInfo({
        pageNo: 1,
        pageSize: 6,
      });
      setRightTopDomList(rightDom(res7.result?.list!));
      setRightBottomDomList(rightDom2(res8.result?.list!));
    })();
  }, []);

  const routerPath = (index: number, item?: AllType) => {
    if (item && (index === 0 || index === 1 || index === 3 || index === 4)) {
      router.push({
        pathname: columns[index].router,
        query: {
          categoryId: item.id,
          name: item.categoryName,
        },
      });
    } else {
      router.push({
        pathname: columns[index].router,
      });
    }
  };

  const handleTenderApply = async (item: NewsTenderType) => {
    if (item.apply) return;
    if (userInfo) {
      let res = await listNewsApi.tenderApply({
        tenderInfoId: item.id,
        tenderNewsId: item.tenderNewsId,
        userAccountId: userInfo.id,
      });
      try {
        if (res.code === '200') {
          message.success('申请成功');
          let res8 = await listNewsApi.listNewTenderInfo({
            pageNo: 1,
            pageSize: 6,
          });
          setRightBottomDomList(rightDom2(res8.result?.list!));
        } else {
          message.error(res.message);
        }
      } catch (e) {
        console.log(e);
      }
    } else {
      setNeedLogin(true);
    }
  };

  const leftDom = (
    item: ColumnsType,
    index: number,
    resultList: Array<Array<AllType>>,
    option: [],
  ) => {
    return (
      <div key={item.title} className='item'>
        <div className='item-title'>
          <div className='item-left'>
            <div className='item-left-label' onClick={() => routerPath(index)}>
              {item.title}
            </div>
          </div>
          <div key={item.title}>
            <Select
              className='select-box'
              placeholder='筛选'
              labelInValue
              onChange={(value) => onMoreChange(value, index, option)}
              bordered={false}
              dropdownMatchSelectWidth={false}
              options={option}
              fieldNames={{
                value: 'categoryName',
                label: 'categoryName',
              }}
            />
          </div>
        </div>
        <div className='item-body'>
          <Space size={[15, 0]} wrap>
            {index === 2
              ? list.map((item, index) => (
                  <div
                    key={item}
                    className={`item-bubble ${
                      index === 0 || index === 1 || index === 2 ? 'active' : ''
                    }`}
                  >
                    {item}
                  </div>
                ))
              : index === 5
              ? list2.map((item, index) => (
                  <div
                    key={item}
                    className={`item-bubble ${
                      index === 0 || index === 1 || index === 2 ? 'active' : ''
                    }`}
                  >
                    {item}
                  </div>
                ))
              : resultList[index]?.map((item, indexer) => {
                  return (
                    <div
                      key={item.categoryName}
                      className={`item-bubble ${
                        indexer === 0 || indexer === 1 || indexer === 2 ? 'active' : ''
                      }`}
                      onClick={() => routerPath(index, item)}
                    >
                      {item.categoryName}
                    </div>
                  );
                })}
          </Space>
        </div>
      </div>
    );
  };

  const rightDom = (list: Array<NewsPageType>) => {
    if (!list?.length) return;
    return (
      <div key={1009} className='right-box-item right-item'>
        <div className='title'>
          <div className='title-label' onClick={() => router.push('/projectInfo')}>
            行业新闻
          </div>
        </div>
        <div className='body'>
          {list?.map((item, index) => (
            <div
              key={item.id}
              className='body-item'
              onClick={() => router.push(`/projectInfo/newsArticle/${item.id}`)}
            >
              <div
                className={`item-ranking ${index === 0 ? 'one' : ''} ${index === 1 ? 'two' : ''} ${
                  index === 2 ? 'san' : ''
                }`}
              >
                {index + 1}
              </div>
              <div className='item-label' title={item.newsTitle}>
                {item.newsTitle}
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  };

  const rightDom2 = (list: Array<NewsTenderType>) => {
    if (!list?.length) return;
    return (
      <div key={1008} className='right-box-item right-item-second'>
        <div className='item-box'>
          <div className='title'>
            <div className='title-label' onClick={() => router.push('/projectInfo')}>
              招标快讯
            </div>
          </div>
          <div className='body'>
            {list?.map((item) => (
              <div key={item.id} className='body-item'>
                <div className='item-label' title={item.tenderTitle}>
                  {item.tenderTitle}
                  <div className='label-bottom'>{item.tenderPrice}</div>
                </div>
                <div
                  className={`item-right ${item.apply ? 'apply' : ''}`}
                  onClick={() => handleTenderApply(item)}
                >
                  <div className='left'>{bigNumberTransform(item.tenderPrice * 10000, true)}</div>
                  {item.apply ? (
                    <div className='right'>已申请</div>
                  ) : (
                    <>
                      <div className='right'>申请合作</div>
                    </>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    );
  };

  return (
    <Box>
      <ContentBox
        boxIndex={1} //分为左右两列，每列一个,从上而下
        leftcontentstyle={{
          width: '806px',
          margin: { top: 0, right: '10px', bottom: '10px', left: 0 },
        }}
        leftWaterfallDom={{
          columns: [{ noFor: true, element: <RotationChart key={45645645} /> }, ...leftDomList],
        }}
        rightRenderDom={{
          columns: [
            { element: <Map key={1001} /> },
            { element: rightTopDomList as JSX.Element },
            { element: rightBottomDomList as JSX.Element },
          ],
        }}
      />
    </Box>
  );
}
