import React, { useEffect, useState } from 'react';
import {
  Card,
  Button,
  Table,
  Space,
  Modal,
  Popconfirm,
  notification,
  Spin,
  Pagination,
} from 'antd';
import copy from 'copy-to-clipboard';
import PageContainer from '@/components/BasePageContainer';
import styles from './ManagementDataBase.less';
import {
  tableCheck,
  tableCheckNew,
  updateDateBase,
  databaseStandardGetLog,
  databaseStandardGetLogNew,
} from '@/services/database/api';
import { CheckSquareFilled, ConsoleSqlOutlined } from '@ant-design/icons';

const ManagementDataBase = () => {
  const [autoCheckList, setAutoCheckList] = useState([]); // 自动列表
  const [checkList, setCheckList] = useState([]); // 手动列表
  const [logList, setLogList] = useState([]); // 日志列表
  const [checkFlag, setCheckFlag] = useState(1);
  const [upFlag, setUpFlag] = useState(1); //
  const [checkLoading, setCheckLoading] = useState(false); // 按钮loading
  const [logLoading, setLogLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false); // 弹窗
  const [content, setContent] = useState(null);
  const [modalTitle, setModalTitle] = useState('详细信息');
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [checkSql, setCheckSql] = useState('');
  const [sqlVisible, setSqlVisible] = useState(false);
  // 检查数据库表
  useEffect(() => {
    setCheckLoading(true);
    // tableCheck({
    //   _version: 9999,
    //   _dc: new Date().getTime(),
    // })
    //   .then(res => {
    //     setCheckLoading(false);
    //     console.log(res);
    //     if (res.sucess) {
    //       const { list, messageList } = res;
    //       // 自动检测列表
    //       let arr = list.map((item, index) => {
    //         item.key = index;
    //         return item;
    //       });
    //       // 手动检查列表
    //       let arr2 = messageList.map((item, index) => {
    //         item.key = index;
    //         return item;
    //       });
    //       setAutoCheckList(arr);
    //       setCheckList(arr2);
    //     }
    //   })
    //   .catch(err => {
    //     setCheckLoading(false);
    //     console.error(err);
    //   });
    tableCheckNew()
      .then(resnew => {
        setCheckLoading(false);
        console.log(resnew);
        if (resnew.code == 0) {
          let res = resnew.data;
          const { Autolist, ManualList } = res;
          // 自动检测列表
          let arr = Autolist.map((item, index) => {
            item.key = index;
            return item;
          });
          // 手动检查列表
          let arr2 = ManualList.map((item, index) => {
            item.key = index;
            return item;
          });
          setAutoCheckList(arr);
          setCheckList(arr2);
        }
      })
      .catch(err => {
        setCheckLoading(false);
        console.error(err);
      });
  }, [checkFlag]);
  // 获取数据库升级记录
  useEffect(() => {
    setLogLoading(true);
    // databaseStandardGetLog({
    //   _version: 9999,
    //   _dc: new Date().getTime(),
    // })
    //   .then(res => {
    //     setLogLoading(false);
    //     if (res) {
    //       let arr = [];
    //       res.map((item, index) => {
    //         item.key = index;
    //         arr.push(item);
    //       });
    //       setLogList(res);
    //     }
    //   })
    //   .catch(err => {
    //     setLogLoading(false);
    //     console.error(err);
    //   });
    databaseStandardGetLogNew()
      .then(resnew => {
        setLogLoading(false);
        if (resnew.code == 0) {
          let res = resnew.data.list;
          let arr = [];
          res.map((item, index) => {
            item.key = index;
            arr.push(item);
          });
          setLogList(res);
        }
      })
      .catch(err => {
        setLogLoading(false);
        console.error(err);
      });
  }, [upFlag]);
  // 检查功能
  const handleCheck = () => {
    setCheckFlag(checkFlag + 1);
  };
  // 升级功能
  const handleUpdate = () => {
    setCheckLoading(true);
    updateDateBase()
      .then(res => {
        setCheckLoading(false);
        setCheckFlag(checkFlag + 1);
        setUpFlag(upFlag + 1);
        if (res.code === 0) {
          notification.success({
            message: '通知',
            duration: 3,
            description: '修复成功',
          });
        } else {
          notification.error({
            message: '通知',
            duration: 15,
            description: res.msg,
          });
        }
      })
      .catch(err => {
        setCheckLoading(false);
        console.error(err);
      });
  };
  const handleErrLog = (text, val) => {
    setModalTitle(val);
    let arr = [];
    arr.push(text.split(/(\r\n)|(\n)/).map((item, index) => <p key={index}>{item}</p>));
    setModalVisible(true);
    // setContent(text);
    setContent(arr);
  };
  const handleLog = (text, val) => {
    setModalTitle(val);
    let arr = [];
    arr.push(text.split(/(\r\n)|(\n)/).map((item, index) => <p key={index}>{item}</p>));
    setModalVisible(true);
    // setContent(text);
    setContent(arr);
  };
  // 复制SQL
  const copySql = text => {
    if (copy(text)) {
      notification.success({
        message: '提示',
        duration: 3,
        description: '复制成功',
      });
    } else {
      notification.error({
        message: '提示',
        duration: 3,
        description: '复制失败',
      });
    }
  };
  const autoCheckColumns = [
    {
      title: '表名称',
      dataIndex: 'TableName',
      key: 'TableName',
      width: 200,
      ellipsis: true,
    },
    {
      title: '类型',
      dataIndex: 'Type',
      key: 'Type',
      width: 180,
      ellipsis: true,
    },
    {
      title: '差异比较',
      dataIndex: 'Message',
      key: 'message',
    },
  ];
  const checkColumns = [
    {
      title: '表名称',
      dataIndex: 'TableName',
      key: 'TableName',
      width: 200,
      ellipsis: true,
    },
    {
      title: '差异比较',
      dataIndex: 'Message',
      key: 'Message',
      width: 400,
      ellipsis: true,
    },
    {
      title: 'SQL语句',
      dataIndex: 'DiffSql',
      key: 'DiffSql',
      render: (text, record) => (
        <Button
          size="small"
          type="primary"
          onClick={() => {
            // copySql(text);
            check(record);
            setSqlVisible(true);
          }}
        >
          查看SQL
        </Button>
      ),
    },
  ];
  const logColumns = [
    {
      title: '登录名',
      dataIndex: 'UpdateBy',
      key: 'UpdateBy',
      width: 200,
      ellipsis: true,
    },
    {
      title: '数据库名称',
      dataIndex: 'Name',
      key: 'Name',
      width: 200,
      ellipsis: true,
    },
    {
      title: '解决方案',
      dataIndex: 'DbProductName',
      key: 'DbProductName',
      width: 200,
      ellipsis: true,
    },
    // {
    //   title: '数据库版本',
    //   dataIndex: 'Version',
    //   key: 'Version',
    //   width: 200,
    //   ellipsis: true,
    // },
    {
      title: '升级时间',
      dataIndex: 'UpdateTime',
      key: 'UpdateTime',
      width: 200,
      ellipsis: true,
    },
    // {
    //   title: '版本日志',
    //   dataIndex: 'Oklog',
    //   key: 'Oklog',
    //   render: text => (
    //     <Button
    //       size="small"
    //       disabled={!text}
    //       onClick={() => {
    //         handleLog(text, '版本日志');
    //       }}
    //     >
    //       日志
    //     </Button>
    //   ),
    // },
    {
      title: '成功日志',
      dataIndex: 'Oklog',
      key: 'Oklog',
      ellipsis: true,
      render: text => (
        <Button
          size="small"
          type="primary"
          onClick={() => {
            handleLog(text, '详细信息');
          }}
        >
          升级内容
        </Button>
      ),
    },
    {
      title: '错误日志',
      dataIndex: 'Errlog',
      key: 'Errlog',
      ellipsis: true,
      render: text => {
        if (text && text.length > 0) {
          return (
            <Button
              size="small"
              type="primary"
              onClick={() => {
                handleLog(text, '详细信息');
              }}
              style={{ backgroundColor: 'red' }}
            >
              错误内容
            </Button>
          );
        }
      },
    },
  ];

  const paginationChange = (page, pageSizes) => {
    console.log(page);
    console.log(pageSizes);
    setCurrentPage(page);
    setPageSize(pageSizes);
  };

  const check = e => {
    console.log(e);
    setCheckSql(e);
  };
  return (
    <>
      <PageContainer>
        <Card>
          <div className={styles.tableTitle}>表结构自动化修复</div>
          <Spin tip="loading..." spinning={checkLoading}>
            <Table
              className={styles.mgTop20}
              columns={autoCheckColumns}
              dataSource={autoCheckList}
              bordered
              size="small"
            />
            <div className={styles.btnBox}>
              <Space>
                <Button type="primary" onClick={handleCheck}>
                  检查
                </Button>
                <Popconfirm
                  title="
                是否升级当前连接数据库?"
                  okText="确认"
                  cancelText="取消"
                  onConfirm={() => {
                    handleUpdate();
                  }}
                >
                  <Button danger type="primary">
                    升级
                  </Button>
                </Popconfirm>
              </Space>
            </div>
          </Spin>
        </Card>
        <Card className={styles.mgTop20}>
          <div className={styles.tableTitle}>
            手动修复 （字段长度不统一，请手动修改差异，数据可能会截断，请谨慎操作）
          </div>
          <Table
            className={styles.mgTop20}
            columns={checkColumns}
            dataSource={checkList}
            bordered
            loading={checkLoading}
            size="small"
          />
        </Card>
        <Card className={styles.mgTop20}>
          <div className={styles.tableTitle}>数据库版本记录</div>
          <Table
            className={styles.mgTop20}
            columns={logColumns}
            dataSource={logList}
            bordered
            loading={logLoading}
            size="small"
          />
        </Card>
      </PageContainer>

      <Modal
        title={modalTitle}
        visible={modalVisible}
        keyboard={false}
        maskClosable
        centered
        onOk={() => setModalVisible(false)}
        onCancel={() => setModalVisible(false)}
        width="1000px"
        bodyStyle={{
          minHeight: '100px',
          maxHeight: '600px',
          overflowY: 'scroll',
        }}
        style={{ top: '40px' }}
        footer={[
          <Button type="primary" onClick={() => setModalVisible(false)} key="back">
            关闭窗口
          </Button>,
        ]}
      >
        {content}
      </Modal>
      <Modal
        title={checkSql.TableName}
        visible={sqlVisible}
        maskClosable
        centered
        onOk={() => setSqlVisible(false)}
        onCancel={() => setSqlVisible(false)}
        width="500px"
        bodyStyle={{
          minHeight: '100px',
          overflowY: 'scroll',
        }}
        footer={[
          <Button type="primary" onClick={() => copySql(checkSql.DiffSql)}>
            复制SQL
          </Button>,
          <Button type="primary" onClick={() => setSqlVisible(false)} key="back">
            关闭窗口
          </Button>,
        ]}
      >
        {checkSql.DiffSql}
      </Modal>
    </>
  );
};

export default ManagementDataBase;
