import {useAppDispatch, useAppSelector} from "../../../redux/configureStore";
import {useCallback, useRef, useState} from "react";
import { PlusOutlined } from '@ant-design/icons';
import {ProTable,ProCard} from '@ant-design/pro-components';
import {Button, message, Modal} from 'antd';

import {
  createDimension,
  deleteDimensions,
  getDimensions,
  getDomains,
  getModals,
  updateDimension
} from "../MainPage/slice/thunks";
import {columnsFactory} from "../../../utils/columnsFactory";
import {ProTableDefault, STATUS_TYPE, TYPE_ENUM} from "../../constants";
import {selectDimensions} from "../MainPage/slice/selectors";
import useMount from "../../hooks/useMount";
import useI18NPrefix from "../../hooks/useI18NPrefix";
import {styled} from "styled-components";
import {DimensionForm} from "./DimensionForm";
import {TreeMenu} from "../../components/TreeMenu";

export const DimensionManage = () => {
  const t = useI18NPrefix('global');
  const dispatch = useAppDispatch();
  const [columns, setColumns] = useState([]);
  const dataRef = useRef({modalId:0});
  const rowRef = useRef(null);
  const dimensions = useAppSelector(selectDimensions);
  const [openModal,setOpenModal]=useState(false);
  const [treeData,setTreeData] = useState([]);
  const baseColumns = [
    {
      title: t("columns.model"),
      dataIndex: 'modelName',
    },
    {
      title: t("columns.dimension"),
      dataIndex: 'name',
    },
    {
      title: t("columns.description"),
      dataIndex: 'description',
    },
    {
      title: t("columns.bizName"),
      dataIndex: 'bizName',
    },
    {
      title: t("columns.status"),
      dataIndex: 'status',
      valueType: 'select',
      valueEnum: STATUS_TYPE,
    }
  ];
  /** 初始渲染的钩子 */
  useMount(
    ()=>{
      // 获取主题域
      dispatch(getDomains(initTreeData))

      // 格式化表头
      setColumns(
        columnsFactory({
          dataSource: baseColumns,
          onEdit:handleEdit,
          onDelete:({id},reload)=>{
            dispatch(deleteDimensions({
              id,
              resolve(){
                reload()
              }
            }))
          }
        })
      )
    },
    ()=>{}
  )

  const initTreeData = (domain)=>{
    function initDomain(data) {
      return data.map(item=>{
        let newItem = item
        if (item.children && item.children.length > 0) {
          newItem.children = initDomain(item.children)
        }
        newItem.isLeaf = false;
        return newItem
      })
    }
    setTreeData(initDomain(domain))
  }

  /** 打开 新增、编辑 对话框 */
  const handleEdit=(row)=>{
    rowRef.current=row?row:null;

    if (row?.id||dataRef.current.modalId){
      setOpenModal(true)
    }else {
      message.warning("请先选择模型")
    }

  };

  /** 提交表单 */
  const onSubmit = useCallback((values)=> {
    if (values.id){
      dispatch(updateDimension({
        params:{
          modelId:dataRef.current.modalId,
          ...values,
          ext: {time_format: values.dateFormat }
        },
        resolve(){
          setOpenModal(false)
          message.success(t("validation.success"))
          dispatch(getDimensions({id:dataRef.current.modalId}))
        }
      }))
    }else {
      dispatch(createDimension({
        params:{
          modelId:dataRef.current.modalId,
          status:1,
          ...values,
          ext: {time_format: values.dateFormat }
        },
        resolve(){
          setOpenModal(false)
          message.success(t("validation.success"))
          dispatch(getDimensions({id:dataRef.current.modalId}))
        }
      }))
    }

  },[]);

  // 插入异步数据
  const updateTreeData = (treeData, id, list) =>
    treeData.map(node=>{
      if (node.id===id){
        const children = (list||[]).map(item=>({
          isLeaf: true,
          title: item.label,
          key: 'dim_' + item.id,
          id: item.id,
          value: item.id,
          type:TYPE_ENUM.DIMENSION,
          parentId:id,
          pId:id,
          children: []
        }))
        return {
          ...node,
          children,
        }
      }
      if (node.children) {
        return {
          ...node,
          children: updateTreeData(node.children, id, list),
        };
      }
      return node
    })

  /** 侧边栏主题域钩子 */
  const onSelect = useCallback((keys, {node}) => {
    if (node?.type===TYPE_ENUM.DIMENSION){
      if (node?.value){
        dataRef.current.modalId = node?.value
        dispatch(getDimensions({id:node?.value}))
      }
    }

  },[]);

  /** 展开主题域 */
  const onTreeNodeExpand=(_, {expanded,node})=>{
    if (expanded && node.typeEnum===TYPE_ENUM.DOMAIN && node.children?.length===0){
      dispatch(getModals({
        domainId:node.id,
        resolve(list){
          setTreeData(
            updateTreeData(treeData,node.id,list)
          )
        }
      }))
    }
  }

  return (
    <>
      <ProCard gutter={8} ghost>
        <ProCard
          bordered
          headerBordered
          colSpan="20%"
          title={t("title.models")}
          style={{height:'85vh'}}
        >
          <TreeMenu treeData={treeData} onExpand={onTreeNodeExpand} onSelect={onSelect}/>
        </ProCard>
        <ProCard bordered={false} bodyStyle={{padding: 0}} style={{backgroundColor:'inherit',height:'85vh'}}>
          <ProTable
            {...ProTableDefault}
            headerTitle={t("title.dimensions")}
            columns={columns}
            dataSource={dimensions}
            request={async () => {
              if (dataRef.current?.modalId){
                await dispatch(getDimensions({id:dataRef.current.modalId}))
              }
            }}
            pagination={{
              pageSize: 20,
              onChange: (page) => console.log(page),
            }}
            toolBarRender={() => [
              <Button
                key="button"
                icon={<PlusOutlined/>}
                onClick={() => handleEdit()}
                type="primary"
              >
                {t("button.create")}
              </Button>
            ]}
          />
        </ProCard>
      </ProCard>
      <CustomModal
        width={1000}
        title={<Title children={t("button.create")}/>}
        open={openModal}
        footer={null}
        maskClosable={false}
        destroyOnClose
        onCancel={()=>setOpenModal(false)}
      >
        <DimensionForm initialValues={rowRef.current} onFinish={onSubmit}/>
      </CustomModal>
    </>
  );
}

const Title = styled.div`
  margin-left: 24px;
`
const CustomModal = styled(Modal)`
  .ant-modal-content{
    padding: 24px 0;
  }
`