import { useEffect, useMemo, useRef, useState } from 'react';
import { TinyArea, TinyColumn } from '@ant-design/charts';
import { Card, Col, Progress, Row, Tabs, DatePicker, Select, Form, Statistic, Button, Spin, Space } from 'antd';
import numeral from 'numeral';
import { ChartCard, Field } from './Charts';
import type { DataItem } from '../data.d';

import { getAsyncOrgTree, getEduUnitList,getExaminationStatistics } from '../service';
const { Option } = Select;
import cookie from 'react-cookies';
import styles from '../style.less';
import ProForm, { ProFormSelect } from '@ant-design/pro-form';
import { useRequest } from 'umi';
import {listMyLearningChapterCourse} from "../../../../../../web/src/pages/course/list/service";
import {number} from "prop-types";
const { RangePicker } = DatePicker;

const topColResponsiveProps = {
  xs: 24,
  sm: 4,
  md: 4,
  lg: 4,
  xl: 4,
  offset: 1,
  style: { marginBottom: 24 },
};

const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};

let city_id=0;
let area_id=0;
let school=0;
const IntroduceRow = ({ loading, visitData }: { loading: boolean; visitData: DataItem[] }) => {
  const [provinceId, setProvinceId] = useState(cookie.load('background_province_id') )
  const [cityList, setCityList] = useState([]);
  const [areaList, setAreaList] = useState([{id:0,name:'全部'}]);

  const [schoolList, setSchoolList] = useState([]);
  const [area, setArea] = useState(0);

  const [options, setOptions] = useState([]);
  const [fetching, setFetching] = useState(false);
  const fetchRef = useRef(0);
  console.log('areaareaarea',area)
  const { loading: courseBrowseTimesLoading, data: eduUnitList = null } = useRequest(() => getEduUnitList({
    random_num: 277470,
    area_id: provinceId,
    edu_type: -1,
    // main_school_id: 200125116,
    // org_name:"",
    org_type: 2,
    pageNumber: 1,
    pageSize: 1000,
    school_type: -1,
    showPassWord: true,
  }), {
    formatResult: (result) => {
      return result.table_List;
    }
  });

  const {data: examinationData, run } = useRequest(() => {
    return getExaminationStatistics({
      bureau_id:typeof (school)===number?school:0,
      city_id:city_id,
      district_id: area_id,
      province_id: provinceId
    });
  },{
    formatResult: (result) => {
      if(result.credential_person_count===0||result.apply_person_count===0){
        const num=0;
        result.num=num;
      }else {
        const percent=result.credential_person_count/result.apply_person_count;
        const num=percent.toFixed(2);
        result.num=num;
      }

      return result;
    }
  });



  //  获取市数据
  const { data: cityData, loading: cityLoading } = useRequest(() => {
    return getAsyncOrgTree({
      org_id: provinceId,
      org_type: 1,
      get_next: 1
    });
  },{
    formatResult: (result) => {
      return result;
    }
  });

  const [form] = Form.useForm();

  // eslint-disable-next-line react-hooks/exhaustive-deps
  useEffect(() => {
    setCityList(cityData || []);
  }, [cityData]);


  const getAreaData = async (e: any) => {
    const areaData = await getAsyncOrgTree({
      org_id: e,
      org_type: 2,
      get_next: 1
    });
    form.setFieldsValue({ area: 0 })
    const list=[{id:0,name:'全部'}];
    const areaList=list.concat(areaData);
    setAreaList(areaList);
    console.log('areaareaListareaListareaListList',areaList)
    run()
  }

  // const getSchoolData = async (e) => {
  //
  //   const schoolData = await getEduUnitList({
  //       random_num: 277470,
  //       area_id: provinceId,
  //       edu_type: -1,
  //       // main_school_id: 200125116,
  //       org_name: e,
  //       org_type: 2,
  //       pageNumber: 1,
  //       pageSize: 1000,
  //       school_type: -1,
  //       showPassWord: true,
  //     })
  //   retrun [{label:'aaaa', value:'1111'},{label:'aaaa', value:'1111'}]
  // }


  const onFinish = (values: any) => {
    // console.log(values);
  };

  const onGenderChange = (value: string) => {

    // const options = this.state.data.map(d => <Option key={d.value}>{d.text}</Option>);


  };

  /**
   * 学校下拉搜索
   * @param value
   */
  const handleSearch = async (value: any) => {
    if (value >= 'a' && value <= 'z') {
      return false;
    }
      if (value) {
      school=value;
      // console.log('value::', value)
      // setOptions([{ORG_NAME:"aaa", ORG_ID:"111"},{ORG_NAME:"aab", ORG_ID:"112"}])
      let id=provinceId;
      if(city_id!==0){
        if(area_id!==0){
          id=area_id;
        }else {
          id=city_id;
        }
      }
      console.log('iddidididididididi',id)
      const { table_List } = await getEduUnitList({
        random_num: 277470,
        area_id: id,
        edu_type: -1,
        // main_school_id: 200125116,
        org_name: value,
        org_type: 2,
        pageNumber: 1,
        pageSize: 1000,
        school_type: -1,
        showPassWord: true,
      });


      setOptions(table_List);
    } else {
      setOptions([]);
    }

  };

  return (
    <Card loading={loading} bordered={false} bodyStyle={{ padding: 0, marginBottom: '24px' }}>
      <Row gutter={16}>
        <Col>
          <Form form={form} name="control-hooks" onFinish={onFinish} layout='inline' style={{padding:'24px 24px 0px 24px'}}>
            <Form.Item name="city" label="市" >
              <Select
                style={{ width: 120 }}
                defaultValue={0}
                onChange={(id) => {
                  city_id=id;
                  if(id!==0){
                    getAreaData(id)
                  }else {
                    area_id=0;
                    setArea(0)
                    setAreaList([{id:0,name:'全部'}])
                    run();

                    console.log('area-----',area);
                    console.log('areaList-----',areaList);
                  }


                }}
              // defaultValue={provinceId}
              >
                <Option key={0} value={0}>全部</Option>
                {
                  cityList.length!==0?
                    cityList.map((item)=>{
                      return <Option key={item.id+'city'} value={item.id}>{item.name}</Option>
                    }):''
                }
              </Select>
            </Form.Item>
            <Form.Item name="area" label="区" >
              {console.log('')}
              <Select
                key={area}
                style={{ width: 120 }}
                defaultValue={0}
                value={area}
                onChange={(id) => {
                  area_id=id;
                  setArea(id)
                  handleSearch('');
                  run()
                }}
              >
                {/*<Option key={0} value={0}>全部</Option>*/}
                {
                  areaList.length!==0?
                    areaList.map((item)=>{
                      return <Option key={item.id+'area'} value={item.id}>{item.name}</Option>
                    }):''
                }
              </Select>
            </Form.Item>
            <Form.Item name="school" label="学校">
              <Select
                showSearch
                style={{ width: 220 }}
                // value={this.state.value}
                // placeholder={this.props.placeholder}
                // style={this.props.style}
                // defaultActiveFirstOption={true}
                defaultActiveFirstOption={false}
                showArrow={true}
                filterOption={false}
                // onChange={getSchoolData}
                notFoundContent={fetching ? <Spin size="small" /> : null}
                // fieldNames={{ value: "ORG_ID", label: "ORG_NAME" }}
                onSearch={handleSearch}
                allowClear={true}
                onClear={()=>{
                  console.log('清空')
                  school=0;
                  run();
                }}
                onChange={(e)=>{
                  console.log('e.target.value',e)
                  if(e!==undefined){
                    school=e;
                    run();
                  }

                }}
                // options={options}
              >
              {
                options.length!==0?
                  options.map((item)=>{
                    return <Option key={item.ORG_ID+'school'} value={item.ORG_ID}>{item.ORG_NAME}</Option>
                  }):''
              }
              </Select>
            </Form.Item>
            </Form>
          </Col>
      </Row>
      <Row gutter={[24, 0]} style={{padding:'0 24px 10px 24px'}}>
        <Col xs={14} sm={14} md={14} lg={14} xl={14} style={{padding:12}}>
          <Row gutter={24} style={{padding:12, border:'solid 1px #f0f0f0', height:'100%'}} >
            <Col xs={8} sm={8} md={8} lg={8} xl={8}>
              <Statistic title="资质考试数" value={examinationData?examinationData.examination_count:'--'} suffix="次" style={{fontSize:16,fontWeight:500}} />
            </Col>
            <Col xs={8} sm={8} md={8} lg={8} xl={8}>
              <Statistic title="累计报名人数" value={examinationData?examinationData.apply_person_count:'--'} suffix="人" style={{fontSize:16,fontWeight:500}}  />
            </Col>
            <Col xs={8} sm={8} md={8} lg={8} xl={8}>
              <Statistic title="取得证书人数" value={examinationData?examinationData.credential_person_count:'--'} suffix="人" style={{fontSize:16,fontWeight:500}}  />
            </Col>
          </Row>
        </Col>
        <Col xs={10} sm={10} md={10} lg={10} xl={10} style={{padding:12}}>
          <ChartCard
            bordered={false}
            loading={loading}
            title={<span style={{fontSize:16,fontWeight:500}}>通过率</span>}
            action={false}
            // total={`${numeral(6560).format('0,0')}`}
            footer={false}
            contentHeight={92}
            style={{ textAlign: 'center', marginBottom: 0 , padding:12, border:'solid 1px #f0f0f0'}}
            bodyStyle={{padding:0}}
          >
            <Progress type="circle" percent={examinationData?parseInt(examinationData.num*100):0} width={80} strokeWidth={10} style={{ position: 'relative', margin: '15px auto 0 auto' }} />
          </ChartCard>
        </Col>
      </Row>
    </Card >)


};

export default IntroduceRow;
