import {useCallback, useMemo, useRef, useState} from 'react';
import moment from "moment";
import {styled} from 'styled-components';
import {Button, Descriptions, Divider} from 'antd';
import {ProCard, ProFormSelect, ProFormText, QueryFilter, ProFormCheckbox} from '@ant-design/pro-components';
import {CheckCardList} from '../../components/CheckCardList.jsx';
import {TreeMenu} from '../../components/TreeMenu';
import {useAppDispatch, useAppSelector} from "../../../redux/configureStore";
import {selectDomains, selectIndexLibs} from "../MainPage/slice/selectors";
import {
  FORM_TYPE,
  INDEX_TYPE,
  SEN_COLOR_LEVEL,
  SENSITIVE,
  STATUS_COLOR_LEVEL
} from "../IndexDefine/constants";
import {
  collectionIndicators,
  deleteCollectionIndicators,
  getDomains,
  getIndexByConditions,
  getIndexDetail,
  queryDimensions
} from "../MainPage/slice/thunks";
import {IndexDetail} from "../IndexDefine/components/IndexDetail";
import useMount from "../../hooks/useMount";
import {useWorkFlow} from "../../hooks/useWorkFlow";
import {PUBLISH_TYPE, STATUS_TYPE} from "../../constants";
import CollectButton from "../../components/CollectButton";
import {selectCurrentUser} from "../../slice/selectors";
import useI18NPrefix from "../../hooks/useI18NPrefix";

export const IndexLibraryPage = () => {
  const t = useI18NPrefix('global');
  const dispatch = useAppDispatch();
  /** 流程图组件钩子*/
  const { clear } = useWorkFlow();
  /** 当前主题名称 */
  const [subTile,setSubTitle]=useState(t("title.baseInfo"));
  /** 指标卡片详情 */
  const [openDetail,setOpenDetail] = useState(false);
  /** 主题域 */
  const domains = useAppSelector(selectDomains);
  /** 指标列表 */
  const indexLib = useAppSelector(selectIndexLibs);
  /** 当前用户信息 */
  const currentUser = useAppSelector(selectCurrentUser);
  /** 数据缓存*/
  const commonRef = useRef({
    treeSelect: {
      id:0,
      name:t("title.models")
    },
    indexDetail:{}
  });

  useMount(
    ()=>{
      dispatch(getDomains());
    },
    ()=>{
      clear();
    }
  )

  /** 侧边栏主题域钩子 */
  const onSelect = useCallback((keys, info) => {
    const {node} = info;
    if (node?.children?.length===0) {
      commonRef.current.treeSelect=keys;
      commonRef.current.ser = 9
      dispatch(getIndexByConditions({
        params:{
          domainIds: keys,
          isPublish:1,
        }
      }))
    }else {
      commonRef.current.treeSelect=0
    }
  },[]);

  /** 双击打开详情 */
  const onCardDoubleClick = useCallback((event)=>{
    const {value,title,tag} = event;
    dispatch(getIndexDetail({
      id:value,
      resolve(detail){
        dispatch(queryDimensions({
          params:{
            ids:detail.drillDownDimensions.map(v=>v.dimensionId),
          },
          resolve(data){
            commonRef.current.indexDetail= {
              ...detail,
              title,
              tag,
              dimensions:data.list
            }
            setOpenDetail(true)
          }
        }))
      }
    }))
  },[]);

  /** 收藏回调*/
  const onCollect=(status,id)=>{
    const params = {
      collectId:id,
      username:currentUser?.username
    }
    if (status){
      dispatch(collectionIndicators({params}))
    }else {
      dispatch(deleteCollectionIndicators({id}))
    }

  }

  /** 指标列表 */
  const cardOption = useMemo(()=>
    (indexLib||[]).map((item)=>({
      title: item.name,
      tag:FORM_TYPE[item.type],
      value:item.id,
      description:item.description,
      extra:[<CollectButton checked={item?.isCollect} onClick={(status)=>onCollect(status,item.id)}/>],
      content:(
        <CustomDescriptions column={5}>
          <Descriptions.Item label={t("formItem.domain")}>{item.domainName}</Descriptions.Item>
          <Descriptions.Item label={t("formItem.metricCode")}>{item.bizName}</Descriptions.Item>
          <Descriptions.Item label={t("formItem.sensitiveLevel")} contentStyle={{color:SEN_COLOR_LEVEL[item.sensitiveLevel]}} children={SENSITIVE[item.sensitiveLevel]}/>
          <Descriptions.Item label={t("formItem.lastVersionNo")}>无</Descriptions.Item>
          <Descriptions.Item label={t("formItem.status")} contentStyle={{color:STATUS_COLOR_LEVEL[item.status]}} children={STATUS_TYPE[item.status]}/>
          <Descriptions.Item label={t("formItem.caliber")}>{item.alias}</Descriptions.Item>
          <Descriptions.Item label={t("formItem.director")}>{item.createdBy}</Descriptions.Item>
          <Descriptions.Item label={t("formItem.creator")}>{item.createdBy}</Descriptions.Item>
          <Descriptions.Item label={t("formItem.createDate")}>{moment(item.createdAt).format('YYYY-MM-DD hh:mm:ss')}</Descriptions.Item>
          <Descriptions.Item label={t("formItem.isPublish")} contentStyle={{color:STATUS_COLOR_LEVEL[item.isPublish]}} children={PUBLISH_TYPE[item.isPublish]}/>
        </CustomDescriptions>
      )
    }))
    ,[indexLib]
  )

  const onCardSelect = useCallback((e)=>setSubTitle(e),[])

  /** 关闭详情 */
  const onDetailClose = useCallback(()=>{
    setOpenDetail(false)
  },[]);

  /** 侧边栏主题域搜索钩子 */
  const onSearch = useCallback((keys) => {},[]);

  const onFilterFinish=useCallback((value)=>{
    const domainIds = commonRef.current.treeSelect;
    if (domainIds>0) {
      dispatch(getIndexByConditions({
        params:{
          hasCollect:value?.collected && value?.collected[0],
          isPublish:1,
          domainIds,
        }
      }))
    }else {
      commonRef.current.treeSelect=0
    }
  },[])


  return (
    <ProCard gutter={8} ghost>
      {/** 指标明细面板 */}
      <IndexDetail
        title={t("title.metricDetail")}
        open={openDetail}
        onClose={onDetailClose}
        values={commonRef.current.indexDetail}
      />
      {/** 左侧的主题与目录 */}
      <ProCard bordered headerBordered colSpan="20%" title={t("title.domain")} style={{height:'85vh'}}>
        <TreeMenu treeData={domains} onSearch={onSearch} onSelect={onSelect}/>
      </ProCard>
      {/** 主面板 */}
      <ProCard bordered headerBordered title={subTile} bodyStyle={{height:'80vh',display:"flex",flexDirection:'column'}} style={{height:'85vh'}}>
        {/** 筛选栏 */}
        <div style={{width:'100%'}}>
          <QueryFilter labelWidth={0} onFinish={onFilterFinish}>
            <ProFormText name="name" placeholder={t("placeholder.metric")} />
            <ProFormSelect
              name="type"
              valueEnum={INDEX_TYPE}
              placeholder={t("formItem.metricType")}
            />
            <ProFormSelect
              name="sensitiveLevel"
              valueEnum={SENSITIVE}
              placeholder={t("formItem.sensitiveLevel")}
            />
            <ProFormCheckbox.Group
              name="collected"
              options={[
                {label:t("operation.collected"),value:true}
              ]}
            />
          </QueryFilter>
          <Span>
            <CustomButton>{t("button.batchCollect")}</CustomButton>
            <CustomButton>{t("button.batchUnCollect")}</CustomButton>
          </Span>
          <Divider style={{margin:'6px 0'}}/>
        </div>

        {/** 指标库列表 */}
        {/** 指标列表 */}
        <div style={{flexShrink: 1,overflow:"hidden",padding:15}}>
          <CheckCardList
            type="checkBox"
            tooltip={t("placeholder.doubleClick")}
            options={cardOption}
            onSelect={onCardSelect}
            onDoubleClick={onCardDoubleClick}
          />
        </div>
      </ProCard>
    </ProCard>
  )
}
const Span = styled.span``;
const CustomButton = styled(Button)`
  margin-left: 25px;
`;
const CustomDescriptions = styled(Descriptions)`
  .ant-descriptions-item-content {
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
`;