import {ProCard, ProFormCheckbox, ProFormSelect, ProFormText, QueryFilter} from "@ant-design/pro-components";
import {useAppDispatch, useAppSelector} from "../../../redux/configureStore";
import { selectIndexLibs} from "../MainPage/slice/selectors";
import { Button, Col, Descriptions, Divider, Row, Space, Spin} from "antd";
import React, {useCallback, useEffect, useMemo, useRef, useState} from "react";
import {styled} from "styled-components";
import {CodeOutlined, LeftOutlined, LikeOutlined, MessageOutlined, StarOutlined} from "@ant-design/icons";
import {FORM_TYPE, INDEX_TYPE, SEN_COLOR_LEVEL, SENSITIVE, STATUS_COLOR_LEVEL} from "../IndexDefine/constants";
import useI18NPrefix from "../../hooks/useI18NPrefix";
import {CheckCardList} from "../../components/CheckCardList";
import {
  collectionIndicators,
  deleteCollectionIndicators, getIndexByConditions,
  getIndexDetail,
  queryDimensions
} from "../MainPage/slice/thunks";
import CollectButton from "../../components/CollectButton";
import {PUBLISH_TYPE, STATUS_TYPE} from "../../constants";
import moment from "moment/moment";
import {selectCurrentUser} from "../../slice/selectors";
import {CardMeta} from "../../components/CardMeta";
import {request} from "../../../utils/request";
import {IndexDetail} from "../IndexDefine/components/IndexDetail";

export const IndexLibraryPage = () => {
  const t = useI18NPrefix('global');
  const dispatch = useAppDispatch();
  /** 指标列表 */
  const indexLib = useAppSelector(selectIndexLibs);
  /** 当前用户信息 */
  const currentUser = useAppSelector(selectCurrentUser);
  /** 当前主题名称 */
  const [domain,setDomain]=useState({});
  /** 主题域列表*/
  const [domainList,setDomainList]=useState([]);
  /** 指标加载状态 */
  const [loading,setLoading]=useState(false);
  /** 指标卡片详情 */
  const [openDetail,setOpenDetail] = useState(false);
  /** 数据缓存*/
  const commonRef = useRef({
    treeSelect: {
      id:0,
      name:t("title.models")
    },
    indexDetail:{}
  });

  const getDomainList = async () =>{
    const {data} = await request({
      url: '/semantic/domain/list'
    })
    setDomainList(data||[])
  }

  useEffect(()=>{
    getDomainList()
  },[])

  /** 双击打开详情 */
  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 onDetailClose = useCallback(()=>{
    setOpenDetail(false)
  },[]);

  /** 收藏回调*/
  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")}>{item?.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 onMetricSelect = useCallback(()=>{},[]);

  const onDomainSelect = useCallback(async (record)=> {
    setLoading(true)
    const data = await dispatch(getIndexByConditions({
      params:{
        domainIds: [record?.id],
        isPublish:1,
      }
    }))
    if (data){
      setLoading(false)
      setDomain(record)
    }
  },[]);

  /** 主题域卡片列表 */
  const cardList = useMemo(()=>{
    const IconText = ({ icon, text ,divider }) => (
      <>
        <Space>
          {React.createElement(icon)}
          {text}
        </Space>
        {divider && <Divider type="vertical"/>}
      </>
    );
    return domainList.map((item,index)=>
      <Col span={6} key={index} onClick={()=>onDomainSelect(item)}>
        <CardMeta
          title={item?.name}
          author={item?.createdBy}
          extra={<Button color="primary" size="small" variant="filled" icon={<CodeOutlined />}>应用</Button>}
          description={item?.description || '暂无描述'}
          action={[
            <IconText icon={StarOutlined} text="156" key="list-vertical-star-o" divider/>,
            <IconText icon={LikeOutlined} text="156" key="list-vertical-like-o" divider/>,
            <IconText icon={MessageOutlined} text="2" key="list-vertical-message" />
          ]}
        />
      </Col>
    )
  },[domainList])

  const onComeback = ()=>setDomain(null)


  const onFilterFinish=useCallback((value)=>{
    console.log(value)
    dispatch(getIndexByConditions({
      params:{
        hasCollect:value?.collected && value?.collected[0],
        isPublish:1,
        ...value,
        domainIds:[domain?.id],
      }
    }))
  },[domain])


  return (
    <ProCard bodyStyle={{height:'85vh',display:"flex",flexDirection:'column'}}>
      {/** 指标明细面板 */}
      <IndexDetail
        title={t("title.metricDetail")}
        open={openDetail}
        onClose={onDetailClose}
        values={commonRef.current.indexDetail}
      />
      <div>
        {
          domain?.id &&
          <CardMeta
            size={32}
            title={domain?.name}
            author={domain?.createdBy}
            description={<a><LeftOutlined/>返回主题</a>}
            onClick={onComeback}
          />
        }
        <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>
        {
          domain?.id &&
          <span>
            <CustomButton>{t("button.batchCollect")}</CustomButton>
            <CustomButton>{t("button.batchUnCollect")}</CustomButton>
          </span>
        }

        <Divider style={{margin: '6px 0'}}/>
      </div>
      <div style={{flexShrink: 1, overflowY: "auto", overflowX: "hidden", padding: 15}}>
      <Spin spinning={loading}>
          {/*指标列表*/}
          {/*主题域卡片*/}
          {
            domain?.id
              ?<CheckCardList
                hoverable
                type="checkBox"
                tooltip={t("placeholder.doubleClick")}
                options={cardOption}
                onSelect={onMetricSelect}
                onDoubleClick={onCardDoubleClick}
              />
              :<Row gutter={[24,24]} children={cardList}/>
          }
        </Spin>

      </div>
    </ProCard>
  )
}

const CustomButton = styled(Button)`
  margin-left: 25px;
`;

const CustomDescriptions = styled(Descriptions)`
  .ant-descriptions-item-content {
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
`;
