import { AndroidOutlined, AppleOutlined, ArrowDownOutlined, ArrowUpOutlined, DeleteOutlined, EditOutlined, EllipsisOutlined, ExclamationCircleOutlined, SettingOutlined, SwapOutlined, TagsOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Divider, message, Drawer, Modal, Tabs, Card, Avatar, Switch, Row, Col, Statistic, Space, Dropdown, Input, Form, Select, SelectProps, MenuProps, Pagination, PaginationProps } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar, PageLoading } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import type { LodingInfo, NewsItem, NewsParams, OptionLog, QADataInfo, QAParams } from './data';
import {
  copyQAItem,
  queryAQAllList,
  queryDeleteList,
  queryQADraftList,
  removeQA,
  removeQADraft,
} from './service';
import MemberAddressModal from "./components/LogsModal";
import LogsModal from "./components/LogsModal";
import Meta from 'antd/lib/card/Meta';

import { MenuInfo } from 'rc-menu/lib/interface';

import { history } from 'umi';
import { queryAllTags } from '../tag/service';
import { NewsDataInfo } from '../subscribe/data';
import { copyNewsItem, removeNews } from '../news/service';


const { confirm } = Modal;


/**
 * 添加文章至草稿
 * @param fields
 */
export const handleCopy = async (fields: QAParams) => {
  const hide = message.loading('创建草稿中...');
  try {
    // fields.deptId = Number(fields.deptId)
    let result = await copyQAItem({ ...fields });
    hide();
    message.success('创建成功');

    console.log("-----result------", result)

    return result;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return {
      data: 0,
      success: false,
    };
  }
};

/**
 *  删除文章
 * @param selectedRows
 */
export const handleRemove = async (currTags: string, selectedRows: NewsItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {

    if (currTags == "1") {
      await removeQA({
        ids: selectedRows.map((row) => row.id),
      });

    } else if (currTags == "3") {
      await removeQADraft({
        ids: selectedRows.map((row) => row.id),
      });
    }


    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

export interface CreateFormProps {
  itemList: QADataInfo[];
  label: number;
  // onCancel: () => void;
  // onSubmit: () => void;
  // addressModalVisible: boolean;
  // memberId: number;
}

const QAList: React.FC<{}> = () => {
  const [addressModalVisible, handleAddressModalVisible] = useState<boolean>(false);
  const [logModalVisible, handleLogModalVisible] = useState<boolean>(false);
  // const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<NewsItem>();
  const [selectedRowsState, setSelectedRows] = useState<NewsItem[]>([]);

  const [initPage, setInitPage] = useState<boolean>(false);
  const [isTime, setIsTime] = useState<boolean>(false);
  const [tag, setTag] = useState<string>();
  const [tagItems, setTagItems] = useState<MenuProps['items']>();
  // const [current, setCurrent] = useState(1);
  // const [pageSize, setPageSize] = useState(10);
  const [logs, setLogs] = useState<OptionLog[]>([]);

  const [isDraft, setIsDraft] = useState<boolean>(false);
  const [currTags, setCurrTags] = useState<string>("1");


  const [options, setOptions] = useState<SelectProps['options']>();


  const [lodingInfos, setLodingInfos] = useState<LodingInfo[]>([
    { total: 0, loding: true, current: 1, pageSize: 10 },
    { total: 0, loding: true, current: 1, pageSize: 10 },
    { total: 0, loding: true, current: 1, pageSize: 10 },
  ]);



  const [allDataInfo, setAllDataInfo] = useState<QADataInfo[]>([]);
  const [deleteDataInfo, setDeleteDataInfo] = useState<QADataInfo[]>([]);
  const [draftDataInfo, setDraftDataInfo] = useState<QADataInfo[]>([]);

  const initTagsFunc = async () => {
    queryAllTags({ pageSize: 1000, current: 0 }).then((res) => {
      console.log("--queryAllTags---->", res)
      setInitPage(true)
      let newRes = res.data

      newRes.map((_item: any, _index: any) => {
        newRes[_index] = {
          ...newRes[_index],
          label: _item.name,
          value: _item.name,
          key: _item.name,
        }
      })

      setTagItems(newRes)

    });
  }

  const initAllFunc = async (current: number, pageSize: number, main_title?: string) => {

    queryAQAllList({ pageSize: pageSize, currentPage: current, order_asc: isTime, tag: tag, main_title: main_title }).then((res: any) => {
      console.log("--queryAQAllList---->", res)

      setInitPage(true)

      const result = res.data

      let newRes = result.data.list as QADataInfo[]

      newRes.map((_item: QADataInfo, _index: any) => {
        newRes[_index] = {
          ...newRes[_index],
        }

      })
      setAllDataInfo(newRes)
      setLodingInfos(prevState => {
        const newState = [...prevState];
        if (newState.length > 2) {
          newState[0].total = result.header.total;
          newState[0].loding = false;
        }
        return newState;
      });

    });


  }

  const initDeleteFunc = (current: number, pageSize: number) => {

    queryAQAllList({ pageSize: pageSize, is_deleted: true, currentPage: current, order_asc: isTime, tag: tag }).then((res: any) => {
      console.log("--queryDeleteList---->", res)

      setInitPage(true)

      const result = res.data
      let newRes = result.data.list as QADataInfo[]

      newRes.map((_item: any, _index: any) => {
        newRes[_index] = {
          ...newRes[_index],
          // label: `${_item.role_name}`, children: `Content of Tab Pane ${_index + 1}`, key: _item.id
        }

      })
      setDeleteDataInfo(newRes)
      setLodingInfos(prevState => {
        const newState = [...prevState];

        console.log("===============>", newState)
        if (newState.length > 2) {
          newState[1].total = result.header.total;
          newState[1].loding = false;
        }
        return newState;
      });

    });


  }


  const initDraftFunc = async (current: number, pageSize: number) => {

    queryQADraftList({ pageSize: pageSize, currentPage: current, order_asc: isTime, tag: tag }).then((res: any) => {
      console.log("--queryQADraftList---->", res)

      setInitPage(true)

      const result = res.data

      let newRes = result.data.list as QADataInfo[]

      newRes.map((_item: any, _index: any) => {
        newRes[_index] = {
          ...newRes[_index],
          // label: `${_item.role_name}`, children: `Content of Tab Pane ${_index + 1}`, key: _item.id
        }

      })
      setDraftDataInfo(newRes)
      setLodingInfos(prevState => {
        const newState = [...prevState];
        if (newState.length > 2) {
          newState[2].total = result.header.total;
          newState[2].loding = false;
        }
        return newState;
      });

    });


  }


  useEffect(() => {
    let isMounted = true
    const fetchPost = async () => {
      if (isMounted) {
        initTagsFunc()
        // initAllFunc()
        // initDeleteFunc()
        // initDraftFunc()
      }
    }

    fetchPost()

    return () => {
      isMounted = false
    }
  }, [])

  useEffect(() => {
    let isMounted = true
    const fetchPost = async () => {
      if (isMounted) {
        initAllFunc(lodingInfos[0].current, lodingInfos[0].pageSize)
        initDeleteFunc(lodingInfos[1].current, lodingInfos[1].pageSize)
        initDraftFunc(lodingInfos[2].current, lodingInfos[2].pageSize)
      }
    }

    fetchPost()

    return () => {
      isMounted = false
    }
  }, [tag, isTime])


  const showDeleteConfirm = (ctag: string, item: NewsItem) => {
    confirm({
      title: '是否删除记录?',
      icon: <ExclamationCircleOutlined />,
      content: `${ctag}: 删除的记录不能恢复,请确认!`,
      onOk() {

        handleRemove(ctag, [item]).then((r) => {
          // actionRef.current?.reloadAndRest?.();
          initAllFunc(lodingInfos[0].current, lodingInfos[0].pageSize)
          initDeleteFunc(lodingInfos[1].current, lodingInfos[1].pageSize)
        });
      },
      onCancel() {
      },
    });
  };

  const CardItemList: React.FC<CreateFormProps> = (props) => {
    const actionRef = useRef<ActionType>();
    const [loading, setLoading] = useState(false);


    const {
      itemList,
      label
      // onSubmit, onCancel, addressModalVisible, memberId 
    } = props;

    return (
      <>
        <Row
          gutter={[24, 16]}
          justify="start"
        // gutter={8}
        // style={{ marginTop: 10 }}
        >
          {
            itemList.map((item, index) => {
              return <Col
                // xs={{ span: 24, offset: 0 }}
                // // sm={{ span: 12, offset: 4 }}
                // // md={{ span: 11, offset: 0 }}
                // lg={{ span: 10, offset: 0 }}
                // xl={{ span: 8, offset: 0 }}
                // xxl={{ span: 6, offset: 0 }}

                key={index}
              >
                <Card
                  style={{ width: 350 }}
                  loading={loading}

                  actions={[

                    // <SettingOutlined key="setting" />,
                    // <EditOutlined key="edit" />,
                    // <EllipsisOutlined key="ellipsis" />,
                  ]}
                >

                  <div

                  >
                    <h5
                      style={{
                        lineHeight: "24px", fontSize: "16px", color: "#333333",

                        overflow: "hidden",
                        textOverflow: "ellipsis",
                        display: "-webkit-box",
                        WebkitLineClamp: 1,
                        WebkitBoxOrient: "vertical",

                      }}
                    >{item.question}</h5>
                    <p
                      style={{
                        lineHeight: "18px", fontSize: "13px", color: "#4D4D4D",

                        overflow: "hidden",
                        // whiteSpace: "nowrap",
                        textOverflow: "ellipsis",

                        display: "-webkit-box",
                        WebkitLineClamp: 3,
                        WebkitBoxOrient: "vertical",

                        minHeight: "58px",

                      }}
                    > {item.answer}</p>
                  </div>

                  <div
                    style={{
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "space-between",
                      fontSize: "12px",
                    }}
                  >
                    <span
                      style={{
                        color: "#808080"
                      }}
                    >{item.created_time}</span>

                    {
                      (label == 1 || label == 2 || label == 3) && <div>
                        <Button type="link" size="small" onClick={async (e) => {
                          console.log("-----编辑", e, item)

                          // message.info('开发中');
                          // history.push(`/article/editqa/${item.id}`);


                          // message.info("开发中")
                          console.log("预创建草稿:", item)
                          if (currTags == "1" || currTags == "2") {
                            const result = await handleCopy(item);
                            if (result.success) {
                              history.push(`/article/editqa/edit/${currTags}/${result.data}`);
                            }
                          } else if (currTags == "3") {
                            history.push(`/article/editqa/edit/${currTags}/${item.id}`);
                          }



                        }}>编辑</Button>

                        {(label == 1 || label == 2 || label == 3) && <Button type="link" size="small" color='#41B670' onClick={async (e) => {
                          console.log("-----订阅", e, item)

                          message.info('开发中');
                          setLogs(item.extra_data.logs == null ? [] : item.extra_data.logs)
                          handleAddressModalVisible(true);

                        }}>查看</Button>}


                        {(label == 1 || label == 3) && <Button type="link" size="small" color='#41B670' onClick={async (e) => {
                          console.log("-----删除", e, item)

                          showDeleteConfirm(currTags, {
                            id: item.id,
                          });

                        }}>删除</Button>}
                      </div>
                    }


                  </div>

                </Card>


              </Col>
            })
          }
        </Row >
        {/* <Switch checked={!loading} onChange={onChange} /> */}

      </>

    );
  };

  const onFinish = (values: any) => {
    console.log('Success:', values);
    resetPage()
    initAllFunc(lodingInfos[0].current, lodingInfos[0].pageSize, values.main_title)
  };

  const resetPage = () => {
    console.log('resetPage:');

    setLodingInfos(prevState => {
      const newState = [...prevState];
      newState.map((r, i) => {
        newState[i].current = 1;
        newState[i].pageSize = 10;
      })

      return newState;
    });

  };



  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };


  const handleButtonClick = (e: React.MouseEvent<HTMLButtonElement>) => {
    // message.info('Click on left button.');
    console.log('click left button', e);


  };

  const handleMenuClick: MenuProps['onClick'] = e => {
    // message.info('Click on menu item.');
    console.log('click', e);
    setTag(e.key)
  };

  const menuProps = {
    items: tagItems,
    onClick: handleMenuClick,
  };

  return (
    <PageContainer >

      {
        (lodingInfos[0].loding || lodingInfos[1].loding || lodingInfos[2].loding) ? <PageLoading />
          :
          <div>
            <div
              style={{
                display: "flex",
                alignItems: "center",
                justifyContent: "space-between",
                fontSize: "12px",
                padding: " 20px 3px"
              }}
            >
              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "space-between",
                  fontSize: "12px",
                }}
              >

                <Form
                  name="basic"
                  // labelCol={{ span: 8 }}
                  // wrapperCol={{ span: 16 }}
                  // initialValues={{ remember: true }}
                  layout="inline"
                  onFinish={onFinish}
                  onFinishFailed={onFinishFailed}
                  autoComplete="off"
                >
                  <Form.Item
                    label="标题:"
                    name="main_title"
                    rules={[{ required: false, message: 'Please input your main title!' }]}
                  >
                    <Input />
                  </Form.Item>


                  <Form.Item shouldUpdate>
                    {() => (
                      <Button
                        type="primary"
                        htmlType="submit"
                      // disabled={
                      //   !form.isFieldsTouched(true) ||
                      //   !!form.getFieldsError().filter(({ errors }) => errors.length).length
                      // }
                      >
                        查询
                      </Button>
                    )}
                  </Form.Item>
                </Form>

                <Button
                  type="primary"
                  onClick={() => {
                    resetPage()
                    setIsTime(false)
                    setTag("")

                  }}
                >
                  重置
                </Button>
              </div>

              <Space wrap size={10}>
                {/* <Button type="primary" >管理</Button> */}
                <Button type="primary" onClick={() => {

                  history.push(`/article/editqa/add`);
                }}>新增</Button>
                {/* <Button type="primary" disabled >删除</Button> */}
              </Space>
            </div>

            <div
              style={{
                position: "relative"
              }}
            >

              <Tabs
                defaultActiveKey="1"
                onChange={(key: string) => {
                  console.log(key);
                  setCurrTags(key)

                }}
                items={[
                  {
                    label: 1,
                    name: `全部(${lodingInfos[0].total})`,
                    icon: AppleOutlined,
                    itemList: allDataInfo,
                  },
                  {
                    label: 2,
                    name: `已删除(${lodingInfos[1].total})`,
                    icon: AndroidOutlined,
                    itemList: deleteDataInfo,
                  },
                  {
                    label: 3,
                    name: `草稿箱(${lodingInfos[2].total})`,
                    icon: AndroidOutlined,
                    itemList: draftDataInfo,
                  },
                ].map((r, i) => {
                  const id = String(i + 1);

                  return {
                    label: (
                      <span>
                        {/* <r.icon /> */}
                        {r.name}
                      </span>
                    ),
                    key: id,
                    children: <div>
                      <CardItemList label={r.label} itemList={r.itemList} />
                      <div
                        style={{
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "center",
                          fontSize: "12px",
                          padding: " 40px 3px"
                        }}
                      >
                        {/* <Pagination total={500} itemRender={itemRender} /> */}
                        <Pagination
                          current={lodingInfos[i].current}
                          pageSize={lodingInfos[i].pageSize}
                          total={lodingInfos[i].total}
                          onShowSizeChange={(current, size) => {
                            console.log("onShowSizeChange: ", current, size)

                            setTimeout(() => {
                              setLodingInfos(prevState => {
                                const newState = [...prevState];
                                newState[i].loding = true;
                                newState[i].current = 1;
                                newState[i].pageSize = size;
                                return newState;
                              });
                            }, 0)




                          }}
                          // showTotal={(total, range) => `${range[0]}-${range[1]} of ${total} items`}

                          onChange={(page) => {
                            console.log("onChange page:", page);

                            setLodingInfos(prevState => {
                              const newState = [...prevState];
                              newState[i].loding = true;
                              newState[i].current = page;
                              return newState;
                            });


                            if (i == 0) {
                              initAllFunc(lodingInfos[i].current, lodingInfos[i].pageSize)
                            } else if (i == 1) {
                              initDeleteFunc(lodingInfos[i].current, lodingInfos[i].pageSize)
                            } else if (i == 2) {
                              initDraftFunc(lodingInfos[i].current, lodingInfos[i].pageSize)
                            }
                          }}
                          defaultPageSize={10}
                          defaultCurrent={1}
                        />
                      </div>
                    </div>

                    ,
                  };
                })}
              />

              <div
                style={{
                  position: "absolute",
                  right: "60px",
                  top: "14px",
                }}

              >
                <Space wrap size={30}>
                  <Dropdown menu={menuProps} >
                    <Button type="text" size="small" onClick={handleButtonClick} icon={<TagsOutlined />}> {!!tag ? tag : "标签"}</Button>
                  </Dropdown>


                  {isTime ?
                    <Button type="text" size="small" icon={<ArrowUpOutlined />}
                      onClick={() => {
                        setIsTime(!isTime)

                        // initAllFunc()
                        // initDeleteFunc()
                        // initDraftFunc()
                      }}
                    > 更新时间</Button> :
                    <Button type="text" size="small" icon={<ArrowDownOutlined />}
                      onClick={() => {
                        setIsTime(!isTime)
                        // initAllFunc()
                        // initDeleteFunc()
                        // initDraftFunc()
                      }}
                    > 更新时间</Button>}

                </Space>


              </div>
            </div>
            <LogsModal
              key={'MemberAddressModal'}
              onSubmit={async () => {
                handleAddressModalVisible(false);
                setCurrentRow(undefined);
                // if (actionRef.current) {
                //   actionRef.current.reload();
                // }
              }}
              onCancel={() => {
                handleAddressModalVisible(false);
                if (!showDetail) {
                  setCurrentRow(undefined);
                }
              }}

              logs={logs}
              addressModalVisible={addressModalVisible}
              memberId={currentRow?.id || 0}
            />

          </div>
      }




    </PageContainer >
  );
};

export default QAList;
