/** 认证考试规则 */
import React, { useState, useRef } from 'react';
import { useParams, useRequest } from 'umi';
import { ExportOutlined, PlusOutlined, TagsOutlined, UploadOutlined } from '@ant-design/icons';
import { Button, message, Input, Drawer, Modal, Col, Row, Space, Upload,Select } from 'antd';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { BetaSchemaForm, ModalForm, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import ProDescriptions from '@ant-design/pro-descriptions';
import type { FormValueType } from './components/UpdateForm';
import UpdateForm from './components/UpdateForm';
import { saveRegistration, removeRegistration, getExaminationPersonApplyList, getAsyncOrgTree } from '../service';
import type { TableListItem, TableListPagination } from './data';
import type { DataItem } from '@antv/data-set/lib/transform/tag-cloud';
const { Option } = Select;
import cookie from 'react-cookies';
/**
 * 添加认证考试规则
 *
 * @param fields
 */

const handleAdd = async (fields: TableListItem) => {
  const hide = message.loading('正在添加');

  try {
    await saveRegistration({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新认证考试规则
 *
 * @param fields
 */

const handleUpdate = async (fields: FormValueType, currentRow?: TableListItem) => {
  const hide = message.loading('正在更新');

  try {
    await saveRegistration({
      ...currentRow,
      ...fields,
    });
    hide();
    message.success('操作成功');
    return true;
  } catch (error) {
    hide();
    message.error('操作失败请重试！');
    return false;
  }
};

/**
 * 删除认证考试规则
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: TableListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeRegistration({
      key: selectedRows.map((row) => row.key),
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const RegistrationList: React.FC = () => {
  const params = useParams();
  console.log('params',params)
  /** 更新窗口的弹窗 */
  const [createModalVisible, handleCreateModalVisible] = useState<boolean>(false);
  const [detailModalVisible, handleDetailModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [provinceId, setProvinceId] = useState("100007")
  const [cityId, setCityId] = useState("0")
  const [areaId, setAreaId] = useState("0")
  const [schoolId, setSchoolId] = useState("0")
  const [exportData, setExportData] = useState({
    examination_id: Number(params.id),

  })



  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<TableListItem>();
  const [selectedRowsState, setSelectedRows] = useState<TableListItem[]>([]);


  const [exportBtn, setExportBtn] = useState(true);
  const [cityList, setCityList] = useState([{id:'0',name:'全部'}]);
  const [areaList, setAreaList] = useState([{id:'0',name:'全部'}]);
  const [schoolList, setSchoolList] = useState([{id:'0',name:'全部'}]);


  const { data:Items } = useRequest(() => {
    return getAsyncOrgTree({
      org_id: cookie.load('background_province_id'),
      org_type: 1,
      get_next: 1
    });
  }, {
    formatResult: (result) => {
      const list=[{name:'全部',id:'0'}]
      setCityList(list.concat(result))
    }
  });

  /** 获取列数据初始值 */
  const getInitialValues = (cols: any[], vals: any) => {
    const initialValues: any[] = [];
    cols.forEach((column: { dataIndex: string }) => {
      const key: any = column?.dataIndex || '';
      initialValues.push({ ...column, initialValue: key ? vals[key] : '' });
    });
    console.log('initialValues',initialValues)
    return initialValues || [];
  };

  /** 列表项定义 */
  const columns: ProColumns<TableListItem>[] = [
    {
      title: '序号',
      key: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '姓名',
      dataIndex: 'person_name',
      valueType: 'text',
      hideInTable: false,
      hideInForm: false,
      hideInSearch: true,
    },
    {

      title: '市',
      dataIndex: 'city_name',
      valueType: 'text',
      sorter: false,
      hideInTable: false,
      hideInForm: false,
      hideInSearch: false,
      fieldProps: {
        allowClear: false
      },
      colSize: 1,
      request: async (params) => {

        const Items = await getAsyncOrgTree({
          org_id: provinceId,
          org_type: 1,
          get_next: 1
        });
        console.log('queryCourseListByTag...', Items)
        const courses = [{ label: "全部", value: 0 }]
        for (let i = 0; i < Items?.length; i++) {
          courses.push({ label: Items[i]?.name, value: Items[i]?.id })
        }
        console.log(courses, 'courses:::');
        // return courses;
      },
      renderFormItem:()=>{
        return(
          <Select allowClear
                  value={cityId}
                  onChange={async(e)=>{
                    console.log('eeeeee',e)
                    if(e!==undefined){
                      setCityId(e);
                      const Items = await getAsyncOrgTree({
                        org_id: e,
                        org_type: 2,
                        get_next: 1
                      });
                      const list=[{name:'全部',id:'0'}]
                      setAreaList(list.concat(Items))
                    }else{
                      setCityId('0');
                      setAreaList([{name:'全部',id:'0'}])
                    }
                    setAreaId('0');
                    setSchoolId('0');
                    setSchoolList([{name:'全部',id:'0'}])
          }}>
            {
              cityList.length!==0?
                cityList.map((item)=>{
                  return <Option  value={item.id}>{item.name}</Option>
                }):''
            }
          </Select>
        )
      }
    },
    {
      title: '区县',
      dataIndex: 'district_name',
      valueType: 'text',
      sorter: false,
      hideInTable: false,
      hideInForm: false,
      hideInSearch: false,
      fieldProps: {
        allowClear: false
      },
      dependencies: ['city_name'],
      request: async (params) => {
        const courses = [{ label: "全部", value: 0 }]

        if (params.city_name) {
          console.log(params, 'params')
          const Items = await getAsyncOrgTree({
            org_id: params.city_name,
            org_type: 2,
            get_next: 1
          });
          console.log('queryCourseListByTag...', Items)
          for (let i = 0; i < Items?.length; i++) {
            courses.push({ label: Items[i]?.name, value: Items[i]?.id })
          }
          console.log(courses, 'courses:::');
        }
        // return courses;

      },
      renderFormItem:()=>{
        return(
          <Select allowClear
                  value={areaId}
                  onChange={async(e)=>{
                    if(e!==undefined){
                      setAreaId(e);
                      const Items = await getAsyncOrgTree({
                        org_id: e,
                        org_type: 3,
                        get_next: 1
                      });
                      const list=[{name:'全部',id:'0'}]
                      setSchoolList(list.concat(Items))
                    }else{
                      setAreaId('0');
                      setSchoolList([{name:'全部',id:'0'}])
                    }
                    setSchoolId('0')
                  }}>
            {
              areaList.length!==0?
                areaList.map((item)=>{
                  return <Option  value={item.id}>{item.name}</Option>
                }):''
            }
          </Select>
        )
      }
    },
    {
      title: '学校',
      dataIndex: 'bureau_name',
      valueType: 'text',
      sorter: false,
      hideInTable: false,
      hideInForm: false,
      hideInSearch: false,
      fieldProps: {
        allowClear: false
      },
      dependencies: ['district_name'],
      request: async (params) => {
        const courses = [{ label: "全部", value: 0 }]

        if (params.district_name) {
          console.log(params, 'params')
          const Items = await getAsyncOrgTree({
            org_id: params.district_name,
            org_type: 3,
            get_next: 1
          });
          console.log('queryCourseListByTag...', Items)
          for (let i = 0; i < Items?.length; i++) {
            courses.push({ label: Items[i]?.name, value: Items[i]?.id })
          }
          console.log(courses, 'courses:::');
        }
        // return courses;

      },
      renderFormItem:()=>{
        return(
          <Select allowClear
                  value={schoolId}
                  onChange={async(e)=>{
                    if(e!==undefined){
                      setSchoolId(e);
                    }else{
                      setSchoolId('0')
                    }

                  }}>
            {
              schoolList.length!==0?
                schoolList.map((item)=>{
                  return <Option  value={item.id}>{item.name}</Option>
                }):''
            }
          </Select>
        )
      }
    },
    {
      title: '考试名称',
      dataIndex: 'examination_name',
      sorter: false,
      valueType: 'select',
      hideInForm: false,
      hideInSearch: true,
      renderText: (val: string) => `${val}`,
    },
    {
      title: '考试时间',
      dataIndex: 'examination_time',
      valueType: 'dateRange',
      sorter: false,
      hideInTable: false,
      hideInForm: true,
      hideInSearch: false,
      render: (dom, entity) => {
        return entity.examination_start_time + "-" + entity.examination_end_time;
      },
    },

  ];

  return (
    <PageContainer>
      <ProTable<TableListItem, TableListPagination>
        headerTitle={false}
        actionRef={actionRef}
        rowKey="registration_id"
        options={false}
        search={{
          labelWidth:70,
          defaultCollapsed:false,
        }}

        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            href={`/dsideal_yy/zygh/training/person/exportPersonApplyData?examination_id=${params.id}`}
            disabled={exportBtn}
          >
            <ExportOutlined /> 导出名单
          </Button>,
        ]}
        request={async (value) => {

          console.log('value', value);
          let examination_time = {}
          if (value.examination_time) {
            examination_time = {
              start_date: value.examination_time[0],
              end_date: value.examination_time[1]
            }
          }
          console.log('value',value)
          value = {
            // ...value,
            is_pass:params.type==='kkwh'?'':1,
            page_number: value.current,
            page_size: value.pageSize,
            city_id: value.city_name,
            district_id:value.district_name,
            bureau_id: value.bureau_name,
            examination_id: params.id,
            ...examination_time
          }
          delete value.examination_time
          // setExportData(value)
          const _data = await getExaminationPersonApplyList(value);
          console.log(_data, '_data 111111')
          _data.totalRow > 0 ? setExportBtn(false) : setExportBtn(true)
          return {
            current: _data?.page_number,
            data: _data?.table_List,
            pageSize: _data?.page_size,
            total: _data?.total_row || 0,
          };
        }}
        // dataSource={list}
        columns={getInitialValues(columns, { city_name: 0, district_name: 0, bureau_name:0})}
      // rowSelection={{
      //   onChange: (_, selectedRows) => {
      //     setSelectedRows(selectedRows);
      //   },
      // }}
      /*
      pagination={{
        showTotal: (total) => {
          return `共 ${total} 条`;
        }
      }}*/
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
          <Button type="primary">批量审批</Button>
        </FooterToolbar>
      )}
      <Modal
        title={currentRow?.registration_name || '课程详细'}
        width="60%"
        visible={detailModalVisible}
        onCancel={() => {
          setCurrentRow(undefined); // 设置当前行
          handleDetailModalVisible(false);
        }}
        footer={null}
        centered
      >{console.log('currentRow', currentRow)}
        {currentRow?.name && (
          <ProDescriptions<TableListItem>
            column={2}
            /* title={currentRow?.name} */
            dataSource={currentRow}
            /*
              request={async () => ({
                data: currentRow || {},
              })}*/
            params={{
              id: currentRow?.registration_id,
            }}
            columns={
              columns
              //columns.slice(0, columns.length - 1) as ProDescriptionsItemProps<TableListItem>[]
            }
          />
        )}
      </Modal>

      <Modal
        title="新建课程"
        //
        width="60%"
        visible={createModalVisible}
        destroyOnClose
        onCancel={() => {
          handleCreateModalVisible(false);
        }}
        footer={null}
      >
        <BetaSchemaForm<DataItem>
          layout="horizontal"
          layoutType="Form"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 12 }}
          onFinish={async (values: any) => {
            // 表单处理
            console.log('columns:', columns);
            console.log('values:', values);

          }}
          submitter={{
            render: (props, doms) => (
              <Row>
                <Col span={12} offset={8}>
                  <Space>{doms}</Space>
                </Col>
              </Row>
            ),
          }}
          // action = ''
          title="新建"
          columns={columns}
        />
      </Modal>

      <Modal
        title="编辑"
        width="60%"
        visible={updateModalVisible}
        destroyOnClose
        onCancel={() => {
          handleUpdateModalVisible(false);
        }}
        footer={null}
      >
        {currentRow?.name && (
          <BetaSchemaForm<DataItem>
            layout="horizontal"
            layoutType="Form"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 12 }}
            onFinish={async (values) => {
              console.log(values);
            }}
            submitter={{
              render: (props, doms) => (
                <Row>
                  <Col span={12} offset={8}>
                    <Space>{doms}</Space>
                  </Col>
                </Row>
              ),
            }}
            // action = ''
            title="编辑"
            columns={getInitialValues(columns, currentRow)}
          />
        )}
      </Modal>
    </PageContainer>
  );
};

export default RegistrationList;
