import {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import moment from "moment";
import {ProCard} from '@ant-design/pro-components';
import {Button, Descriptions, message} from 'antd'
import {styled} from 'styled-components'
import {CheckCardList} from '../../components/CheckCardList.jsx';
import {TreeMenu} from '../../components/TreeMenu';
import {MoreOutlined} from '@ant-design/icons'
import {DomainForm} from "../ModalManage/components/DomainForm";
import {ActionIcon} from "../../components/ActionIcon";
import {IndexCreator} from "./components/IndexCreator";
import {IndexDetail} from "./components/IndexDetail";
import {FORM_TYPE, LOGIC_TYPE, SEN_COLOR_LEVEL, SENSITIVE, STATUS_COLOR_LEVEL} from "./constants";
import {IndexFilterForm} from "./components/IndexFilterForm";
import {STATUS_TYPE, TYPE_ENUM} from "../../constants";
import {ACTION_TYPES} from "../../components/WorkFlow/constants";
import {AuthorizationPanel} from "./components/AuthorizationPanel";
import {VolumeAuthPanel} from "./components/VolumeAuthPanel";
import {useAppDispatch, useAppSelector} from "../../../redux/configureStore";
import {selectDomains, selectIndexLibs} from "../MainPage/slice/selectors";
import {
  batchPublish,
  createDomain,
  createMetric,
  deleteMetric,
  getDomains,
  getIndexByConditions,
  getIndexDetail, getRoles, queryDimensions
} from "../MainPage/slice/thunks";

export const IndexDefine = () => {
  const dispatch = useAppDispatch();
  /** 打开主题域表单 */
  const [domainModalOpen, setDomainModalOpen] = useState(false);
  /** 指标创建表单对话框打开状态 */
  const [openCreator, setOpenCreator] = useState(false);
  /** 指标卡片详情 */
  const [openDetail,setOpenDetail] = useState(false);
  /** 授权面板 */
  const [openAuth,setOpenAuth] = useState(false);
  /** 指标批量授权 */
  const [openIndexAuth,setOpenIndexAuth] = useState(false);
  /** 当前主题名称 */
  const [subTile,setSubTitle] = useState("数据详情");
  /** 数据缓存*/
  const commonRef = useRef({
    treeSelect: {
      id:0,
      name:'模型信息'
    },
    indexCreator:{},
    indexDetail:{}
  });

  /** 主题域 */
  const domains = useAppSelector(selectDomains);
  /** 指标列表 */
  const indexLib = useAppSelector(selectIndexLibs);

  useEffect(()=>{
    /** 获取主题域 */
    dispatch(getDomains());
    dispatch(getRoles({}))
  },[])

  /** 右键打开情景框 */
  const onRightClick=useCallback(({event, node})=>{
    event.preventDefault();
    console.log(node);
  },[]);

  /** 右键情景框选择后回调 */
  const onRightSelect = (event)=>{
    console.log(event)
    if (event.key==='update'){
      setDomainModalOpen(true)
    }
    if (event.key==='auth'){
      setOpenAuth(true)
    }
  }

  /** 主题域表单提交-取消 */
  const handelDomainFormCancel=useCallback(()=>{
    setDomainModalOpen(false)
  },[])

  /** 主题域表单-打开 */
  const handelDomainFormOpen=useCallback(()=>{
    setDomainModalOpen(true)
  },[])

  /** 主题域表单--提交 */
  const domainFormSubmit = useCallback((values) => {
    const {parentId} = values;
    dispatch(createDomain({
      ...values,
      parentId: parentId ? parentId : 0
    }));
  },[])

  /** 左侧主题树目录 */
  const buildTree = useMemo(()=>{
    const items = [
      {
        key: 'update',
        label: "编辑"
      },
      {
        key: 'auth',
        label: "授权管理"
      },
      {
        key: 'remove',
        label: "删除"
      }
    ];
    function insertKey(arr) {
      let temp = [];
      for (const i in arr) {
        const record = arr[i];
        const {children} = record;
        let item = {
          key: record.id,
          title:<ActionIcon trigger="contextMenu" items={items} children={record.title} onSelect={onRightSelect} tooltip="右键编辑"/>,
          data: record,
          isLeaf: children?.length===0,
        }
        if (children?.length>0) {
          item.children = insertKey(children)
        }
        temp.push(item)
      }
      return temp
    }
    return insertKey(domains)
  },[domains]);

  /** 侧边栏主题域钩子 */
  const onSelect = useCallback((keys, info) => {
    const {node} = info;
    if (!node?.children) {
      commonRef.current.treeSelect=node.data;
      dispatch(getIndexByConditions({
        params:{
          domainIds: keys,
          current:1,
          pageSize:999
        },
      }))
    }else {
      commonRef.current.treeSelect={
        id:0,
        name:'模型信息'
      }
    }
  },[]);

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

  /** 筛选表单提交 */
  const onFilterFormFinish = useCallback((e)=>{
    console.log(e)
  },[]);

  /** 选择创建模式-回调 */
  const onModelSelect = useCallback((info) => {
    if (commonRef.current.treeSelect.id){
      commonRef.current.indexCreator.type=info.value
      commonRef.current.indexCreator.sensitiveLevel="0"
      commonRef.current.indexCreator.inovkeMethod='AUTO'
      setOpenCreator(true)
    }else{
      message.error('请先选择主题')
    }

  }, []);

  /** 指标创建表单-提交 */
  const onCreatorFinish = useCallback((values)=>{
    const {decimalPlaces,relateDimension,dateDimension,measure,operations,sensitiveLevel,attributes} = values;
    console.log(values)
    let drillDownDimensions = [];
    if (relateDimension){
      drillDownDimensions.push({
        dimensionId:dateDimension,
        necessary:false,
        inheritedFromModel:false
      })
      relateDimension.forEach(v=>
        drillDownDimensions.push({
        dimensionId:v,
        necessary:false,
        inheritedFromModel:false
      }))
    }
    let defaultConfig = "";
    if (attributes){
      for (let i = attributes.length - 1; i >= 0; i--) {
        const {value,logic,fields,condition} = attributes[i];
        const cdt = condition?condition:""
        if (LOGIC_TYPE[logic]==="包含" || LOGIC_TYPE[logic]==="不包含"){
          defaultConfig +=` ${cdt} ${fields} ${logic} '%${value}%'`
          continue
        }
        if (LOGIC_TYPE[logic]==="为空"||LOGIC_TYPE[logic]==="不为空"){
          defaultConfig +=` ${cdt} ${fields} ${logic}`
          continue
        }
        defaultConfig +=` ${cdt} ${fields} ${logic} ${value} `
      }
    }
    console.log(defaultConfig)
    // 部分字段需再次处理
    const params = {
      ...values,
      sensitiveLevel:parseInt(sensitiveLevel),
      metricDefineByMeasureParams:{
        measures:[
          {
            bizName:measure,
            constraint:"",
            agg:operations
          }
        ],
        expr:measure,
        filterSql:""
      },
      typeEnum:TYPE_ENUM.METRIC,
      dataFormat:{
        needMultiply100:false,
        decimalPlaces:decimalPlaces?decimalPlaces:2,
      },
      relateDimension:{
        drillDownDimensions
      }
    }
    console.log(params);

    // dispatch(createMetric({
    //   params,
    //   resolve(){
    //     dispatch(getIndexByConditions({
    //       params:{
    //         domainIds: [commonRef.current.treeSelect.id],
    //         current:1,
    //         pageSize:999
    //       },
    //     }))
    //   }
    // }))
    //
    // setOpenCreator(false)
  },[]);

  /** 双击打开详情 */
  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)
  },[]);


  /** TODO 卡片Extra选项回调 */
  const onExtraSelect =(event,item)=>{
    const {id,title,tag,type,relateDimension,sensitiveLevel,metricDefineByMeasureParams,metricDefineByMetricParams} = item;
    // 编辑指标
    if (event.key==="update"){
      let bizName,agg
      if (type===FORM_TYPE.ATOMIC.value){
        // 原子指标回显维度
        const measureParams = metricDefineByMeasureParams.measures[0]
        bizName = measureParams.bizName
        agg = measureParams.agg
      }else if (type===FORM_TYPE.COMPOSITE.value){
        // 其他指标回显维度
        const measureParams = metricDefineByMetricParams.metrics[0]
        bizName = measureParams.bizName
        agg = measureParams.agg
      }
      commonRef.current.indexCreator = {
        ...item,
        sensitiveLevel:`${sensitiveLevel}`,
        measure:bizName,
        operations:agg,
        dateDimension: relateDimension.drillDownDimensions[0]?.dimensionId, //parseInt(item?.relaDimensionIdKey.split(',')[0])
        relateDimension:relateDimension.drillDownDimensions.filter((item,index)=>index!==0).map(item=>item.dimensionId)
      }

      setOpenCreator(true)
    }
    // 指标授权
    if (event.key==="auth"){
      setOpenAuth(true)
    }
    // 删除指标
    if (event.key==="remove"){
      dispatch(deleteMetric({
        id,
        resolve(){
          const {id} = commonRef.current.treeSelect
          if (id){
            dispatch(getIndexByConditions({
              params:{
                domainIds: [id],
                current:1,
                pageSize:999
              },
            }))
          }
        }
      }))
    }
    // 指标详情
    if (event.key==="detail"){
      dispatch(getIndexDetail({
        id,
        resolve(data){
          commonRef.current.indexDetail= {...data,title,tag}
          setOpenDetail(true)
        }
      }))
    }
  }

  /** 指标列表 */
  const cardOption = useMemo(()=> indexLib.map((item)=>({
      title: item.name,
      tag:FORM_TYPE[item.type],
      value:item.id,
      description:item.description,
      extra:[
        <ActionIcon
          key={2}
          items={ACTION_TYPES.CHECK}
          onSelect={(event)=>onExtraSelect(event,item)}
        >
          <Button type="link" ><MoreOutlined rotate={90} style={{fontSize:25}}/></Button>
        </ActionIcon>
      ],
      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 handelCreatorClose = useCallback(() => {
    commonRef.current.indexCreator = {}
    setOpenCreator(false)
  }, []);

  /** 卡片选中 */
  const onCardChecked = useCallback((list)=>{
    console.log(list)
    commonRef.current.indexChosen = list.map(item=>({id:item.value,value:item.value,label:item.title}))
  },[]);

  /** 关闭授权面板 */
  const onAuthPanelClose = useCallback(()=>setOpenAuth(false),[])
  /** 关闭授权面板 */
  const onIndexAuthPanelClose = useCallback(()=>setOpenIndexAuth(false),[])
  /** 关闭授权面板 */
  const onIndexAuthPanelOpen = useCallback(()=>setOpenIndexAuth(true),[])
  /** 批量授权回调*/
  const onAuthConfigChange=useCallback((e)=>{console.log(e)},[])
  /** 批量发布按钮回调*/
  const onVolumePublish = useCallback(()=>{
    const {indexChosen} = commonRef.current
    const params = {
      ids:indexChosen.map(item=>item.id),
      status:0,
      type:"ADD"
    }
    dispatch(batchPublish({
      params,
      resolve(data){
        console.log(data)
      }
    }))
  },[])

  return (
    <ProCard gutter={8} ghost>
      {/** 主题域编辑面板 */}
      <DomainForm
        open={domainModalOpen}
        onCancel={handelDomainFormCancel}
        onFinish={domainFormSubmit}
      />

      {/** 创建指标面板 */}
      <IndexCreator
        handleCancel={handelCreatorClose}
        initialValues={commonRef.current.indexCreator}
        onFinish={onCreatorFinish}
        open={openCreator}
      />

      {/** 指标明细面板 */}
      <IndexDetail
        title="指标详情"
        open={openDetail}
        onClose={onDetailClose}
        values={commonRef.current.indexDetail}
      />

      {/** 主题授权管理面板 */}
      <AuthorizationPanel
        open={openAuth}
        onCancel={onAuthPanelClose}
        values={commonRef.current.indexDetail}
      />

      {/** 指标批量授权面板 */}
      <VolumeAuthPanel
        open={openIndexAuth}
        onCancel={onIndexAuthPanelClose}
        onChange={onAuthConfigChange}
        values={commonRef.current.indexChosen}
      />

      {/** 左侧的主题与目录 */}
      <ProCard
        bordered
        headerBordered
        colSpan="20%"
        title="数据集"
        style={{height:'84vh'}}
        extra={<ExtraLink onClick={handelDomainFormOpen}>+新增主题</ExtraLink>}
      >
        <TreeMenu
          onRightClick={onRightClick}
          onSelect={onSelect}
          treeData={buildTree}
          onSearch={onSearch}
        />
      </ProCard>

      {/** 主面板 */}
      <ProCard bordered headerBordered title={subTile} bodyStyle={{overflowY: 'auto',height:'80vh'}}>
        {/** 筛选栏 */}
        <IndexFilterForm onModelSelect={onModelSelect} onFinish={onFilterFormFinish}/>

        <Span>
          <CustomButton onClick={onIndexAuthPanelOpen}>批量授权</CustomButton>
          <CustomButton onClick={onVolumePublish}>批量发布</CustomButton>
        </Span>

        {/** 指标列表 */}
        <CheckCardList
          type="checkBox"
          tooltip="双击显示详情"
          options={cardOption}
          onSelect={onCardSelect}
          onDoubleClick={onCardDoubleClick}
          onChecked={onCardChecked}
          pagination={{
            total: 50,
          }}
        />
      </ProCard>
    </ProCard>
  )
}
const Span = styled.span``;
const CustomButton = styled(Button)`
  margin-left: 25px;
`;
const ExtraLink = styled.a`
  font-size: ${p=>p.theme.fontSizeLG}px;
`