import {useCallback, useMemo, useRef, useState} from 'react';
import moment from "moment";
import {styled} from 'styled-components';
import {Button, Descriptions} 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 {HeartTwoTone} from '@ant-design/icons';
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 {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 {STATUS_TYPE} from "../../constants";

const collectedOption = [
  {label:'只显示我收藏的',value:true}
]
export const IndexLibraryPage = () => {
  const dispatch = useAppDispatch();
  /** 流程图组件钩子*/
  const { clear } = useWorkFlow();
  /** 当前主题名称 */
  const [subTile,setSubTitle]=useState("数据据详情");
  /** 指标卡片详情 */
  const [openDetail,setOpenDetail] = useState(false);
  /** 主题域 */
  const domains = useAppSelector(selectDomains);
  /** 指标列表 */
  const indexLib = useAppSelector(selectIndexLibs);
  /** 数据缓存*/
  const commonRef = useRef({
    treeSelect: {
      id:0,
      name:'模型信息'
    },
    indexDetail:{}
  });

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

  /** 侧边栏主题域钩子 */
  const onSelect = useCallback((keys, info) => {
    const {node} = info;
    console.log(info)
    if (node?.children?.length===0) {
      commonRef.current.treeSelect=keys;
      dispatch(getIndexByConditions({
        params:{
          domainIds: keys,
        },
        resolve(data){console.log(data)}
      }))
    }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 cardOption = useMemo(()=>
    indexLib.map((item)=>({
      title: item.name,
      tag:FORM_TYPE[item.type],
      value:item.id,
      description:item.description,
      extra:[<Button type="link" key={2} children={<HeartTwoTone style={{fontSize:25,color:'red'}}/>}/>],
      content:(
        <Descriptions column={5}>
          <Descriptions.Item label="指标主题">{item.domainName}</Descriptions.Item>
          <Descriptions.Item label="指标编码">{item.bizName}</Descriptions.Item>
          <Descriptions.Item label="敏感度" contentStyle={{color:SEN_COLOR_LEVEL[item.sensitiveLevel]}} children={SENSITIVE[item.sensitiveLevel]}/>
          <Descriptions.Item label="指标版本">无</Descriptions.Item>
          <Descriptions.Item label="指标状态" contentStyle={{color:STATUS_COLOR_LEVEL[item.status]}} children={STATUS_TYPE[item.status]}/>
          <Descriptions.Item label="业务口径">{item.description}</Descriptions.Item>
          <Descriptions.Item label="业务口径负责人">{item.createdBy}</Descriptions.Item>
          <Descriptions.Item label="创建人">{item.createdBy}</Descriptions.Item>
          <Descriptions.Item label="创建时间">{moment(item.createdAt).format('YYYY-MM-DD hh:mm:ss')}</Descriptions.Item>
        </Descriptions>
      )
    }))
    ,[indexLib]
  )

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

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

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


  return (
    <ProCard gutter={8} ghost>
      {/** 指标明细面板 */}
      <IndexDetail
        title="指标详情"
        open={openDetail}
        onClose={onDetailClose}
        values={commonRef.current.indexDetail}
      />
      {/** 左侧的主题与目录 */}
      <ProCard bordered headerBordered colSpan="20%" title="数据集" style={{height:'84vh'}}>
        <TreeMenu treeData={domains} onSearch={onSearch} onSelect={onSelect}/>
      </ProCard>
      {/** 主面板 */}
      <ProCard bordered headerBordered title={subTile} >
        <QueryFilter defaultCollapsed={false} span={4} labelWidth={0} onFinish={(e)=>{console.log(e)}}
           submitter={{
             render: (props, doms) => {
               return [
                 ...doms,
                 <Button htmlType="button" onClick={()=>{}} key="edit">
                   导出
                 </Button>
               ];
             },
           }}
        >
          <ProFormText name="name" placeholder="请输入指标名或指标符" />
          <ProFormSelect
            name="type"
            valueEnum={INDEX_TYPE}
            placeholder="指标类型"
          />
          <ProFormSelect
            name="sensitiveLevel"
            valueEnum={SENSITIVE}
            placeholder="敏感度"
          />
          <ProFormCheckbox.Group
            name="collected"
            options={collectedOption}
          />
        </QueryFilter>
        <Span>
          <CustomButton>批量收藏</CustomButton>
          <CustomButton>批量取消收藏</CustomButton>
        </Span>

        {/** 指标库列表 */}
        <CheckCardList
          type="checkBox"
          tooltip="双击显示详情"
          options={cardOption}
          onSelect={onCardSelect}
          onDoubleClick={onCardDoubleClick}
          pagination={{
            total: 50,
            pageSize:20,
            onShowSizeChange:console.log
          }}
        />
      </ProCard>
    </ProCard>
  )
}
const Span = styled.span``;
const CustomButton = styled(Button)`
  margin-left: 25px;
`;