/* eslint-disable */
import { useContext, useEffect, useState } from 'react';

import {
  Button,
  Cascader,
  Checkbox,
  Form,
  Input,
  Modal,
  Pagination,
  Select,
  Space,
  message,
  Image as AntdImage,
} from 'antd';
import type { CheckboxValueType } from 'antd/es/checkbox/Group';
import Image from 'next/image';
import { useRouter } from 'next/router';

import commonApi from '~/api';
import ContentBox from '~/components/contentBox';
import { TypesResp } from '~/components/filter/api';
import Layout from '~/components/layout';
import { UserContext } from '~/lib/userProvider';
import { phoneNumber } from '~/lib/validateUtils';

import api, { Flying, RegionResp, SkillsType } from './api';
import { Box } from './styled';

interface FilterInfoParams {
  provinceId?: number;
  categoryId?: any[];
}

export default function FlyingHandService() {
  const { Option } = Select;
  const router = useRouter();
  const { userInfo, setNeedLogin } = useContext(UserContext);
  const [list, setList] = useState([
    'https://share-fly.oss-cn-hangzhou.aliyuncs.com/file/540X844-1(1).jpg',
    'https://share-fly.oss-cn-hangzhou.aliyuncs.com/file/540X844(1).jpg',
  ]);
  const [productList, setProductList] = useState(Array<{ element: JSX.Element }>);
  const [rightDomList, setRightDomList] = useState(Array<{ element: JSX.Element }>);
  const [secondDistrictInfo, setSecondDistrictInfo] = useState(Array<RegionResp>);
  const [skills, setSkills] = useState(Array<RegionResp>);
  const [skillsDefault, setSkillsDefault] = useState<Array<number>>();
  const [flightSkillsList, setFlightSkillsList] = useState<Array<SkillsType>>();
  const [flightDefault, setFlightDefault] = useState<number | null>();
  const [selectOption, setSelectOption] = useState<Array<TypesResp> | null>();
  const [selectDefault, setSelectDefault] = useState<number | null>();
  const leftDom = (item: Flying) => {
    return (
      <div
        className='item'
        key={item.id}
        onClick={() => {
          userInfo
            ? router.push({
                pathname: `/flyingHandService/detail/${item.id}`,
              })
            : setNeedLogin(true);
        }}
      >
        <div className='item-top'>
          <Image
            src={
              item.videoUrl
                ? `${item.videoUrl}?x-oss-process=video/snapshot,t_1000,m_fast`
                : item.surfaceUrl
            }
            alt='#'
            fill
          />
        </div>
        <div className='item-bottom'>
          <div className='bottom-title'>{item.curriculumName}</div>
          <div className='bottom-details'>{item.curriculumDesc}</div>
          <div className='bottom-price'>
            <div className='bottom-price-left' title={item.supplierName}>
              {item.supplierName}
            </div>
            <div className='bottom-price-right'>
              {item.free ? (
                <div className='price-right-label'>{item.price}</div>
              ) : (
                <div>
                  <span className='price-right-label'>免费听课</span>
                  {/* <span className='price-right-money'>{`¥${item.price}`}</span> */}
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    );
  };

  const rightDom = (item: string) => {
    return (
      <div className='right-box-item right-item' key={item}>
        <AntdImage src={item} width={260} preview={false} />
      </div>
    );
  };

  const [pageParams, setPageParams] = useState({
    pageNo: 1,
    pageSize: 12,
  }); // 分页器对象

  const [filterParams, setFilterParams] = useState<FilterInfoParams>();

  const [count, setCount] = useState(0); // 商品总数
  const [abort, setAbort] = useState<AbortController | null>(null); // 请求中断

  const onPageChange = (page: number, pageSize: number) => {
    setPageParams({
      ...pageParams,
      pageNo: page,
    });
  };

  useEffect(() => {
    // 中断前一次列表请求
    abort?.abort();
    setAbort(new AbortController());
  }, [filterParams, pageParams]);

  // 端口列表请求
  useEffect(() => {
    console.log(router);

    const queryVal = JSON.parse(JSON.stringify(router.query));
    for (const key in queryVal) {
      queryVal[key] = Number(queryVal[key]);
    }
    api
      .listPageJobServicesInfo({
        ...pageParams,
        ...filterParams,
        ...queryVal,
      })
      .then((res) => {
        setProductList(
          res.result?.list?.map((item) => {
            return { element: leftDom(item) };
          }) || [],
        );
        setCount(res.result?.totalCount || 0);
        clearRouter();
      });
  }, [abort]);

  const clearRouter = () => {
    if (Object.keys(router.query).length) {
      router.query = {};
      router.replace(router.pathname);
    }
  };

  const onSelectChange = (value: number, item: TypesResp) => {
    clearRouter();
    console.log(value);

    if (value) {
      setSelectDefault(value);
    } else {
      setSelectDefault(undefined);
    }
    setFilterParams((props) => {
      if (props?.categoryId && value) {
        return {
          ...props,
          categoryId: [...props.categoryId, Number(value)],
        };
      }
      return {
        ...props,
        categoryId: value ? [Number(value)] : undefined,
      };
    });
  };

  const onProvinceChange = (value: number) => {
    clearRouter();
    if (value) {
      setFlightDefault(value);
    } else {
      setFlightDefault(undefined);
    }
    setFilterParams((props) => {
      return {
        ...props,
        licenseId: Number(value),
      };
    });
  };

  const onChange = (value: any) => {
    clearRouter();
    if (value) {
      setSkillsDefault([value]);
    } else {
      setSkillsDefault([]);
    }
    setFilterParams((props) => {
      return {
        ...props,
        flightSkillsId: (value && value[value.length - 1]) || undefined,
      };
    });
  };

  const onChangeRegion = (value: any) => {
    clearRouter();
    // setFilterParams((props) => {
    //   return {
    //     ...props,
    //     regionId: (value && value[value.length - 1]) || undefined,
    //   };
    // });
    setFilterParams((props) => {
      return {
        ...props,
        provinceId: value || undefined,
      };
    });
  };
  const getPropagandaCenter = () => {
    commonApi.listBannerImg('FLYER_TRAIN').then((res) => {
      setRightDomList(
        (res.result || []).map((item) => {
          return { element: rightDom(item.bannerImg) };
        }),
      );
    });
  };

  useEffect(() => {
    getPropagandaCenter();
    api.region().then((res) => {
      setSecondDistrictInfo(res.result || []);
    });
    // api.PilotLicense().then((res) => {
    //   setSkills(res.result || [])
    // })
    // api.IndustryFlightSkills().then((res) => {
    //   const list = res.result?.map((item) => {
    //     item.label = item.skillsName
    //     item.value = item.id
    //     return item
    //   })
    //   setFlightSkillsList(list || [])
    // })
    api.FlightSkills({ type: 3 }).then((res) => {
      console.log(res);

      setSelectOption(res.result);
    });
  }, []);

  useEffect(() => {
    if (Object.keys(router.query).length) {
      const queryVal = JSON.parse(JSON.stringify(router.query));
      for (const key in queryVal) {
        queryVal[key] = Number(queryVal[key]);
      }
      if (queryVal.flightSkillsId) {
        setSkillsDefault([queryVal.flightSkillsId]);
      } else {
        setFlightDefault(queryVal.licenseId);
      }
      setFilterParams((props) => {
        return {
          ...props,
          ...queryVal,
        };
      });
    }
  }, [router]);

  // 报名
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const handleOk = async (values: any) => {
    form
      .validateFields()
      .then(async (values) => {
        setLoading(true);
        try {
          const res = await api.PilotRegistrations({
            ...values,
            city: values.city[values.city.length - 1] || undefined,
            province: values.city[0] || undefined,
            uavLicenseLevelOne: values.uavLicenseLevelOne && values.uavLicenseLevelOne[0],
            uavLicenseLevelTow: values.uavLicenseLevelOne && values.uavLicenseLevelOne[1],
            uavLicenseLevelThree: values.uavLicenseLevelOne && values.uavLicenseLevelOne[2],
          });
          if (res.code === '200') {
            setLoading(false);
            setIsModalOpen(false);
            form.resetFields();
            message.success('报名成功');
          } else {
            setLoading(false);
            message.error(res.message);
          }
        } catch (e: any) {
          message.error(e.message);
        }
      })
      .catch((err) => {
        message
          .warning({
            content: err.errorFields[0].errors[0],
          })
          .then();
      });
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const [form] = Form.useForm();
  const onChangeCheck = (checkedValues: CheckboxValueType[]) => {
    console.log('checked = ', checkedValues);
  };

  return (
    <Layout>
      <Box>
        <div className='flyingTop'>
          <div className='flyingTop-left'>
            <Space>
              {/* <Cascader
                allowClear
                placeholder="地域"
                bordered={false}
                className="selectItem"
                size="large"
                fieldNames={{
                  label: "name",
                  value: "id",
                  children: "childInfo",
                }}
                options={secondDistrictInfo}
                onChange={onChangeRegion}
                changeOnSelect
              /> */}
              {/* <Select
                className="selectItem"
                bordered={false}
                popupMatchSelectWidth={false}
                placeholder="省份"
                size="large"
                onChange={onChangeRegion}
                options={secondDistrictInfo}
                fieldNames={{ value: 'id', label: 'name' }}
                allowClear
              /> */}
              {/* {selectOption?.map((item) => (
                <Select
                  key={item.directoryId}
                  className="selectItem"
                  bordered={false}
                  popupMatchSelectWidth={false}
                  placeholder={item.name}
                  size="large"
                  onChange={(value) => onSelectChange(value, item)}
                  options={item.categoriesInfoListDTO}
                  fieldNames={{ value: 'id', label: 'name' }}
                  allowClear
                />
              ))} */}
            </Space>
          </div>
          <Button
            type='primary'
            className='btn'
            onClick={() => (userInfo ? setIsModalOpen(true) : setNeedLogin(true))}
          >
            报名学习课程
          </Button>
        </div>
        <Modal
          wrapClassName='application'
          title={<div className='title'>报名学习课程</div>}
          open={isModalOpen}
          onCancel={handleCancel}
          getContainer={false}
          footer={[
            <Button
              style={{
                width: '100%',
                background: 'linear-gradient(135deg, #278EFF 0%, #0052DA 100%)',
                height: 40,
              }}
              key='submit'
              type='primary'
              loading={loading}
              onClick={handleOk}
            >
              立即报名
            </Button>,
          ]}
        >
          <Form
            form={form}
            layout='vertical'
            name='application'
            initialValues={{ modifier: 'public' }}
          >
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <Form.Item
                style={{ flex: 1, marginRight: 16 }}
                name='name'
                rules={[{ required: true, message: '请输入姓名!' }]}
              >
                <Input placeholder='姓名' />
              </Form.Item>
              <Form.Item
                style={{ flex: 1 }}
                name='telephone'
                rules={[{ required: true, message: '请输入手机号!' }]}
              >
                <Input onInput={phoneNumber} allowClear maxLength={11} placeholder='手机号' />
              </Form.Item>
            </div>
            <Form.Item name='city' rules={[{ required: true, message: '请选择城市!' }]}>
              <Cascader
                allowClear
                placeholder='城市'
                className='selectItem'
                fieldNames={{
                  label: 'name',
                  value: 'id',
                  children: 'childInfo',
                }}
                options={secondDistrictInfo}
                changeOnSelect
              />
            </Form.Item>

            <Form.Item name='drivingLicense'>
              <Select allowClear placeholder='是否有驾照'>
                <Option value='0'>是</Option>
                <Option value='1'>否</Option>
              </Select>
            </Form.Item>
            <Form.Item name='uavLicenseLevelOne'>
              <Cascader
                allowClear
                placeholder='是否有无人机执照'
                className='selectItem'
                fieldNames={{
                  label: 'licenseType',
                  value: 'id',
                  children: 'childLicenses',
                }}
                options={skills}
                changeOnSelect
              />
            </Form.Item>
            <Form.Item
              name='industryAppAuth'
              label='行业应用认证（多选）'
              className='collection-create-form_last-form-item'
            >
              <Checkbox.Group options={flightSkillsList} onChange={onChangeCheck} />
            </Form.Item>
            <Form.Item name='remark'>
              <Input placeholder='备注' />
            </Form.Item>
          </Form>
        </Modal>

        <ContentBox
          boxIndex={4}
          leftcontentstyle={{
            width: '925px',
            margin: { top: 0, right: '10px', bottom: '10px', left: 0 },
          }}
          leftRenderDom={{
            columns: productList,
            pagination: (
              <div className='pagination-page'>
                <Pagination
                  current={pageParams.pageNo}
                  pageSize={pageParams.pageSize}
                  showSizeChanger={false}
                  showQuickJumper
                  total={count}
                  onChange={onPageChange}
                  hideOnSinglePage={true}
                  style={{ marginTop: 20 }}
                />
              </div>
            ),
          }}
          rightRenderDom={{ columns: rightDomList }}
        />
      </Box>
    </Layout>
  );
}
