import {memo, useCallback, useEffect, useMemo, useState} from 'react';
import {Button, Descriptions, Divider, Drawer, Table, Tag} from "antd";
import {styled} from "styled-components";
import {UpOutlined} from "@ant-design/icons";
import moment from "moment";
import {ProCard} from "@ant-design/pro-components";
import {PureTableCard} from "../../../components/PureTableCard";
import {FilterPanel} from "../../../components/FilterPanel";
import {WorkFlowPanel} from "../../../components/WorkFlow";
import {useAppDispatch} from "../../../../redux/configureStore";
import {getMetricLineage, queryMetric, queryTask} from "../../MainPage/slice/thunks";
import {PUBLISH_STATUS, SEN_COLOR_LEVEL, SENSITIVE, STATUS_COLOR_LEVEL, TASK_STATUS} from "../constants";
import {useWorkFlow} from "../../../hooks/useWorkFlow";
import {MetricNode} from "../../../components/WorkFlow/atomic/MetricNode";
import {STATUS_TYPE} from "../../../constants";
const columns = [
  {
    title: '调度时间',
    dataIndex: 'startTime',
    key: 'startTime'
  },
  {
    title: '指标版本',
    dataIndex: 'lastVersionNo',
    key: 'lastVersionNo',
  },
  {
    title: '任务状态',
    dataIndex: 'state',
    key: 'state',
    render: (text) => <Tag color={text?"success":"volcano"}>{TASK_STATUS[text]}</Tag>
  },
  {
    title: '操作人',
    key: 'operator',
    dataIndex: 'operator'
  }
];
const data = [
  {
    key: '1',
    startTime:"2024-09-09 12:11:34",
    operator: 'admin',
    lastVersionNo: 'V20240629001',
    state: 0,
  },
  {
    key: '1',
    startTime:"2024-09-10 12:41:33",
    operator: 'admin',
    lastVersionNo: 'V20240629001',
    state: 1,
  },
];
const versionColumns = [
  {
    title: '版本号',
    dataIndex: 'versionNo',
    key: 'versionNo'
  },
  {
    title: '创建人',
    dataIndex: 'creator',
    key: 'creator',
  },
  {
    title: '创建日期',
    dataIndex: 'createDate',
    key: 'createDate',
  },
  {
    title: '创建状态',
    dataIndex: 'status',
    key: 'status',
    render: (text) => <Tag color={text?"success":"volcano"}>{PUBLISH_STATUS[text]}</Tag>,
  },
  {
    title: '发布人员',
    dataIndex: 'publisher',
    key: 'publisher',
  },
  {
    title: '发布日期',
    dataIndex: 'publishDate',
    key: 'publishDate',
  }
];

export const IndexDetail = memo(({
 open,
 title,
 onClose,
 values,
}) => {
  const {clear,updateNodesState,updateEdgesState,getNodesState,getEdgesState} = useWorkFlow();
  const dispatch = useAppDispatch();
  const [otherOpen, setOtherOpen] = useState(true);
  const [tab, setTab] = useState('tab1');
  const [queryData,setQueryData] = useState({});

  const formatNodes = (data,position)=>{
    const {children} = data;
    let initNodes = [];
    let initEdges = [];
    initNodes.push({
      id: `${data.metricId}`,
      type:'metric',
      data: {
        label:data.metricName,
        width:data.metricName.length * 25,
      },
      position
    })
    if (children) {
      children.forEach((item,index)=>{
        const newPosition = {
          x:position.x + data.metricName.length * 35,
          y:(position.y*0.5)+index*90,
        }
        initEdges.push({
          id: `${data.metricId}-${item.metricId}`,
          style: {strokeWidth: 1, stroke: 'black'},
          source: `${data.metricId}`,
          target: `${item.metricId}`
        })
        const {nodes,edges} = formatNodes(item,newPosition)
        initNodes = [...initNodes,...nodes]
        initEdges = [...initEdges,...edges]
      })
    }
    return {
      nodes:initNodes,
      edges:initEdges
    }
  }

  useEffect(() => {
    if (open && values.id){
      dispatch(getMetricLineage({
        id:values.id,
        resolve(data) {
          const {nodes,edges} = formatNodes(data,{x: 100, y: 100})
          updateNodesState(nodes)
          updateEdgesState(edges)
        }
      }))

      dispatch(queryTask({
        id:values.id,
        resolve(data) {
          console.log(data)
        }
      }))
    }
    return () => {
      clear()
    };
  }, [open,values]);


  /** 筛选条件更改时的回调处理*/
  const onLogicChange = ({days, dimension, tags}) => {
    const {id, domainId} = values;
    const params = {
      domainId,
      limit: 1,
      metricIds: [id],
      metricNames: [],
      dimensionIds: (dimension||[]).map(item=>item.value),
      dimensionNames: [],
      dateInfo: {
        dateMode: "BETWEEN",
        startDate: moment().subtract(days ? days : 0, 'days').format('YYYY-MM-DD'),
        endDate: moment().format('YYYY-MM-DD'),
        dateList: [],
        unit: 1,
        period: "day",
        detectWord: "",
        isInherited: false,
        groupByDate: false
      },
      filters:(tags||[]).map(v=>({
        relation: "FILTER",
        id: v.value,
        bizName: v.bizName,
        name: v.name,
        operator: v.condition,
        value: v.keyword,
        children:[]
      })),
    }
    dispatch(queryMetric({
      params,
      resolve(data) {
        setQueryData(data)
      }
    }))
  };

  /** 指标概览模块 */
  const LogicPanel = useMemo(() => {
    const {columns,resultList} = queryData;
    const queryColumns = (columns||[]).map(item=> (
      {
        title: item.name,
        dataIndex: item.nameEn,
        key: item.nameEn,
      }
    ))
    console.log(values)
    return <>
      <FilterPanel
        delay={1000}
        options={{
          dimension:(values?.dimensions || []).map(v=>({
            value:v.id,
            label:v.description||v.name,
            bizName:v.bizName
          }))
        }}
        onChange={onLogicChange}
      />
      <Table key="index" columns={queryColumns} dataSource={resultList}/>
    </>
  }, [open,queryData]);

  /** 版本概览模块 */
  const VersionPanel = useMemo(() => (
    <Table columns={versionColumns} dataSource={[]}/>
  ), []);

  /** 调度记录模块 */
  const InvokePanel = useMemo(() => (
    <Table columns={columns} dataSource={data}/>
  ), []);

  /** 标签页切换*/
  const onTabChange = useCallback((tab)=>{
    setTab(tab)
  },[tab,values])


  return (
    <Drawer
      styles={{
        body: {
          padding: '10px 0 10px 30px'
        }
      }}
      width={1230}
      destroyOnClose
      maskClosable={false}
      title={title}
      placement="right"
      open={open}
      onClose={onClose}
    >
      {/** 头信息 及 操作按钮 */}
      <Wrapper>
        <Title>
          {values?.title}
          {values?.tag &&
            <Tag style={{marginLeft: 10}} color={values?.tag.color}>{values?.tag.label}</Tag>
          }
        </Title>
        <Extra>
          <Button type="primary" ghost style={{marginRight: 15}}>基础信息详情</Button>
          <Button type="primary" ghost style={{marginRight: 15}}>新建指标</Button>
          <Button type="primary" ghost style={{marginRight: 15}}>复制指标</Button>
        </Extra>
      </Wrapper>
      <Divider style={{margin: '10px 0 10px 0'}}/>
      {/** 信息体 */}
      <Container>
        <Descriptions column={5}>
          <Descriptions.Item label="指标主题">{values.domainName}</Descriptions.Item>
          <Descriptions.Item label="指标编码">{values.bizName}</Descriptions.Item>
          <Descriptions.Item label="敏感度" contentStyle={{color:SEN_COLOR_LEVEL[values.sensitiveLevel]}} children={SENSITIVE[values.sensitiveLevel]}/>
          <Descriptions.Item label="指标版本">{values.lastVersionNo||"V20240629001"}</Descriptions.Item>
          <Descriptions.Item label="指标状态" contentStyle={{color:STATUS_COLOR_LEVEL[values.status]}} children={STATUS_TYPE[values.status]}/>
          <Descriptions.Item label="业务口径">{values.description}</Descriptions.Item>
          <Descriptions.Item label="业务口径负责人">{values.createdBy}</Descriptions.Item>
          <Descriptions.Item label="创建人">{values.createdBy}</Descriptions.Item>
          <Descriptions.Item label="创建时间">
            {moment(values.createdAt).format('YYYY-MM-DD hh:mm:ss')}
          </Descriptions.Item>
        </Descriptions>
        {
          otherOpen && (
            <>
              <PureTableCard title="指标定义" headDivider={true} style={{padding: '5px 0'}}>
                <Descriptions column={5}>
                  <Descriptions.Item label="数据模型">{values.modelName}</Descriptions.Item>
                  <Descriptions.Item label="度量">无</Descriptions.Item>
                  <Descriptions.Item label="计算方式">无</Descriptions.Item>
                  <Descriptions.Item label="数据格式">{values.dataFormatType}</Descriptions.Item>
                  <Descriptions.Item label="小数点位数">{values.dataFormat?.decimalPlaces}</Descriptions.Item>
                  <Descriptions.Item label="时间维度">{values.dateDimId}</Descriptions.Item>
                  <Descriptions.Item label="分析维度">无</Descriptions.Item>
                  <Descriptions.Item label="调度方式">无</Descriptions.Item>
                </Descriptions>
              </PureTableCard>
              <PureTableCard title="调度规则" headDivider={true} style={{padding: '5px 0'}}>
                <Descriptions column={4}>
                  <Descriptions.Item label="调度类型">无</Descriptions.Item>
                  <Descriptions.Item label="出差重试">无</Descriptions.Item>
                  <Descriptions.Item label="调度周期">无</Descriptions.Item>
                  <Descriptions.Item label="指定时间">无</Descriptions.Item>
                  <CustomItem label="依赖任务" contentStyle={{display: 'block'}}>
                    <Table columns={columns} dataSource={data} pagination={false} size='small'/>
                  </CustomItem>
                </Descriptions>
              </PureTableCard>
            </>
          )
        }
        <Footer onClick={() => {setOtherOpen(!otherOpen)}}>
          { otherOpen ? '收起' : '展开'} <UpOutlined rotate={otherOpen ? 0 : 180}/>
        </Footer>

        {/** 指标的其他信息 */}
        <ProCard
          tabs={{
            activeKey: tab,
            items: [
              {
                label: `指标概览`,
                key: 'tab1',
                children: LogicPanel,
              },
              {
                label: `指标血缘`,
                key: 'tab2',
                children: (
                  <WorkFlowPanel
                    nodeTypes={{metric:MetricNode}}
                    initialNodes={getNodesState}
                    initialEdges={getEdgesState}
                    style={{height: '43vh',backgroundColor:'white',border:'none'}}
                  />
                ),
              },
              {
                label: `版本信息`,
                key: 'tab3',
                children: VersionPanel,
              },
              {
                label: `调度记录`,
                key: 'tab4',
                children: InvokePanel,
              }
            ],
            onChange: onTabChange,
          }}
        />
      </Container>
    </Drawer>
  )
})

const Container = styled.div`
    width: 100%;
    max-height: 93%;
    overflow-y: auto;
    overflow-x: hidden;
`
const Wrapper = styled.div`
    width: 100%;
    display: flex;
    align-items: center;
    box-sizing: border-box;
`

const Title = styled.div`
    font-size: ${p => p.theme.fontSizeLG}px;
    font-weight: bold;
    display: inline-block;
    flex: 1;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    box-sizing: border-box;
`

const Extra = styled.div`
    margin-inline-start: auto;
    color: ${p => p.theme.colorTextBase};
    font-weight: normal;
    font-size: 14px;
    box-sizing: border-box;
`
const Footer = styled.a`
    margin-left: 95%;
`
const CustomItem = styled(Descriptions.Item)`
    .ant-descriptions-item {
        .ant-descriptions-item-container {
            .ant-descriptions-item-content {
                display: none;
            }
        }
    }

`
