import React, { useState, useRef } from 'react';
import { useRequest, useParams, Link } from 'umi';
import { PlusOutlined, TagsOutlined, UploadOutlined } from '@ant-design/icons';
import { Button, message, Input, Drawer, Modal, Col, Row, Space, Upload, Select, Breadcrumb } 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 type { ProFormInstance } from '@ant-design/pro-form';
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 { saveCertificate, getExaminationPersonApplyList, getAsyncOrgTree } from '../service';
import type { TableListItem, TableListPagination } from '../data';
import type { DataItem } from '@antv/data-set/lib/transform/tag-cloud';
import cookie from 'react-cookies';
/**
 * 添加证书
 *
 * @param fields
 */

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

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


const CourseList: React.FC = () => {
  /** 更新窗口的弹窗 */
  const [createModalVisible, handleCreateModalVisible] = useState<boolean>(false);
  const [detailModalVisible, handleDetailModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const params = useParams();

  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();

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

  /** 列表项定义 */
  const columns: ProColumns<TableListItem>[] = [
    {
      title: '序号',
      key: 'index',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '姓名',
      dataIndex: 'person_name',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '市',
      dataIndex: 'city_name',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '区县',
      dataIndex: 'district_name',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '学校',
      dataIndex: 'bureau_name',
      valueType: 'text',
      hideInSearch: true,
    },

    {
      title: '证书类型',
      dataIndex: 'examination_name',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '市',
      dataIndex: 'city_id',
      valueType: 'select',
      hideInTable: true,
      fieldProps: {
        allowClear: false
      },
      hideInForm: false,
      hideInSearch: false,
      request: async () => {
        const data = await getAsyncOrgTree({
          org_id: cookie.load('background_province_id'),
          org_type: 1,
          get_next: 1
        }).then();
        const option = [{ label: "全部", value: 0 }]
        data?.map((e, i) => {
          option.push({ label: e.name, value: e.id })
        })

        return option;
      },
    },
    {
      title: '区',
      dataIndex: 'district_id',
      valueType: 'select',
      hideInTable: true,
      hideInForm: false,
      hideInSearch: false,
      fieldProps: {
        allowClear: false
      },
      dependencies: ['city_id'],
      request: async (params) => {
        if (params.city_id) {
          console.log(params, 'params::::');
          console.log(formRef, 'formRef::::');
          console.log(formRef.current?.getFieldsValue(['district_id']));
          const option = [{ label: "全部", value: 0 }]


          const data = await getAsyncOrgTree({
            org_id: params.city_id,
            org_type: 2,
            get_next: 1
          }).then();
          formRef.current?.setFieldsValue({ district_id: 0 })

          data?.map((e, i) => {
            console.log(e, i);

            option.push({ label: e.name, value: e.id })
          })
          console.log('area:', data);

          // for (let i = 0; i < Items.length; i++) {
          //   tags.push({ label: Items[i].tag_name, value: Items[i].tag_id })
          // }

          return option;
        }
        const option = [{ label: "全部", value: 0 }]
        return option;
      },
    },
    {
      title: '考试时间',
      valueType: 'dateRange',
      dataIndex: 'examination_time',
      sorter: false,
      hideInTable: false,
      hideInForm: false,
      hideInSearch: false,
      render: (dom, entity) => {
        return entity.examination_start_time + " - " + entity.examination_end_time
      },
    },
    {
      title: '制证状态',
      dataIndex: 'status_type',
      sorter: false,
      valueType: 'text',
      hideInForm: false,
      hideInSearch: true,
      render: (dom, entity) => {
        return params.accreditation_status == 1 ? "已制证" : "未制证";
      },
    },
    {
      title: '姓名或学校',
      dataIndex: 'bureau_name',
      sorter: false,
      valueType: 'text',
      hideInForm: true,
      hideInSearch: false,
      hideInTable: true,

    },


  ];
  /** 获取列数据初始值 */
  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] : '' });
    });
    return initialValues || [];
  };

  return (
    <PageContainer
      header={{
        breadcrumbRender: (props, originBreadcrumb) => {
          return <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/examination/option">考试管理</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              <Link to="/examination/certificate">制证管理</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              <Link to="">{decodeURIComponent(params?.name)}</Link>
            </Breadcrumb.Item>
          </Breadcrumb>
        }
      }}
    >
      <ProTable<TableListItem, TableListPagination>
        headerTitle={false}
        actionRef={actionRef}
        formRef={formRef}
        rowKey="course_id"
        options={false}
        search={{
          labelWidth: 120,
        }}

        request={async (value) => {
          console.log(value, 'form value')
          const { examination_time } = value;
          if (examination_time) {
            value.start_date = examination_time[0]
            value.end_date = examination_time[1]
          }
          delete value.examination_time
          const _data = await getExaminationPersonApplyList({
            ...value,
            examination_id: params.id,
            city_id: value.city_id ? value.city_id : 0,
            district_id: value.district_id ? value.district_id : 0,
            page_number: value.current,
            page_size: value.pageSize, is_pass: 1
          });
          return {
            current: _data?.pageNumber,
            data: _data?.table_List,
            pageSize: _data?.pageSize,
            total: _data?.totalRow || 0,
          };
        }}
        // dataSource={list}
        columns={getInitialValues(columns, { city_id: 0, district_id: 0 })}
        rowSelection={false}
      />

      <Modal
        title={currentRow?.course_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?.course_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"
          // form={schemaForm}
          layoutType="Form"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 12 }}
          // onValuesChange={(values: any) => {
          //   console.log('values:', values);
          //   const { city_id } = values
          //   if (city_id) {
          //     schemaForm.setFieldsValue({ district_id: "" })
          //   }
          // }}

          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 CourseList;
