import React, { useEffect, useRef, useState } from 'react';
import { Button, Dropdown, Form, FormInstance, Input, Menu, Space, Tooltip, Upload } from 'antd';
import { ActionType, ProColumns, ProFormInstance, ProTable } from '@ant-design/pro-components';
import { baseFun, ContextMenu, DictTree, EditType, SDOperate, SDForm, SDFormDict, SDFormText, SDLayout, SDModalForm, SDPage, SDSubmitButton, SDTable, SDTree, TableData,SDButton,SDAreaTtile } from '@sundata/ui-frame';
import { SysFunButtonInfoModel,riskExposureDefinitionModel,riskExposureClassRuleModel } from '@/services/rwa/rwa_calc_config_001riskexposure/info';
import {  getDetail1, getFunTree1,getSelectTreeData,getRiskDataList,createRiskRuleData,updateRiskRuleExistData,delRiskRuleData,createRiskData,updateRiskData,isNotExist,deleteFunc } from '@/services/rwa/rwa_calc_config_001riskexposure/info';
import { DataNode } from 'antd/lib/tree';
import { MenuInfo } from 'rc-menu/lib/interface';
import { SortOrder } from 'antd/es/table/interface';
import { CheckSquareOutlined, CloseSquareTwoTone, PlusSquareTwoTone, WomanOutlined } from "@ant-design/icons";
import { ProductProps } from '@/sundataImport';
import { useModel } from '@umijs/max';
import { number } from 'echarts';
import { method, toNumber } from 'lodash';
import DirectoryTree from 'antd/es/tree/DirectoryTree';

type widowProp = {
  onCancel:  () => void;
  onChangeVisible(visible: boolean, type: string): unknown;
  onChangeVisdible:(visible:boolean,type ?: 'none' | 'raload' )=>void;
}& ProductProps;
const info: React.FC<widowProp> = (prop:widowProp) => {

    /** 编辑方式，查看、修改、新增按钮时设置，详细信息表单中使用 */
    const [editType, setEditType] = useState<EditType>(prop.editType || 'update');
    /** 是否显示详细信息窗口 */
    const [detailVisible, setDetailVisible] = useState<boolean>(false);
    const [currentRow, setCurrentRow] = useState<riskExposureClassRuleModel>();
    /** 表格引用对象，刷新表格使用   */
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance<any>>();
    const proformRef = useRef<FormInstance>();
    const [key, setKey] = useState<any>();
    const [editRuleNo, setEditRuleNo] = useState<any>();
    /** 编辑方式，查看、修改、新增按钮时设置，详细信息表单中使用 */
    const [backEditType, setBackEditType] = useState<EditType>(prop.editType || 'update');
    const backformRef = useRef<FormInstance>();
    /** 表格引用对象，刷新表格使用   */
    const backActionRef = useRef<ActionType>();
    const [treeData, setTreeData] = useState<DictTree[]>();

    const leaf = useRef('1');
    const levelcode = useRef(0);

    const [dataSource, setDataSource] = useState<readonly SysFunButtonInfoModel[]>()
    let runtimeEditType: EditType;
    /** 是否单一权重 显示使用   */
    const [riskFlag,setRiskFlag] = useState<boolean>(false);
    const[riskWeightFlag,setRiskWeightFlag] = useState<boolean>(false);

    // 页面数据
    const[formData,setFormData] = useState<riskExposureClassRuleModel[]>();

    const { fetchDict } = useModel('dict');

  useEffect(() => {
    refreshTree();
  }, []);

  // 获取树结构
  const refreshTree = async () => {
    const newTree = await getFunTree1();
    formatArray(newTree);
    setTreeData(newTree);
  };

  // 树结构图标初始化（新增和废除）
  function formatArray (arr:DictTree[]) {
    arr.forEach((item) => {
     if(Array.isArray(item.children)==false){
      if (item.attribute == '0') {
        item.icon=<CloseSquareTwoTone/>;
      } else {
        item.icon= <CheckSquareOutlined/>;
      }
     };
     Array.isArray(item.children) ? formatArray(item.children) : item;
    });
 }

  // 新建节点
  const createNode = (node: DictTree) => {
    const offobjectNo = node.key as string;
    setEditType('create');
    runtimeEditType = 'create';
    // 设置新增初始值
    formRef.current?.setFieldsValue({
      buttonList: [],
      funccode: '',
      funcname: '',
      num: 0,
      oldfunccode: '',
      orderno: 1,
      parentname: node.title?.toString(),
      remark: '',
      url: '',
    });
    leaf.current = '1';
    levelcode.current = levelcode.current + 1;
  }

  // 废除节点
  const deleteNode = (node: DictTree) => {
    const funccode = node.key;
    if (node.children) {
      baseFun.warning('请先作废所有下级节点');
      return;
    }
    if (treeData?.length === 1 && !treeData[0].children) {
      baseFun.warning('不能作废根节点');
      return;
    }
    baseFun.confirm("请确认是否继续操作", ()=>{  deleteFunc(funccode).then(()=>{
    baseFun.info("作废成功");
    refreshTree();
    });
  });

  }



  // 菜单增加
  const handleSave =async(record:riskExposureDefinitionModel)=>{
    if (editType == 'create') {
      await createRiskData(record).then(()=>{
        baseFun.info("执行成功");
      });
      refreshTree();
      closeAndRefresh();
    } else if (editType == 'update') {
      await updateRiskData(record).then(()=>{
        baseFun.info("执行成功");
        refreshTree();
        closeAndRefresh();
      });
    }
    
  }

  // 风险暴漏规则新增或删除
  const handleRiskRuleSave =async(record:any)=>{
    if (backEditType == 'update' ) {
      if (currentRow?.ruleNo) {
        updateRiskRuleExistData(record,currentRow?.ruleNo);
        closeAndRefresh();
      }
    } else if (backEditType == 'create' ) {
      createRiskRuleData(record,key);
      closeAndRefresh();
    }
  }

    //关闭窗口刷新父页面
    const closeAndRefresh = ()=>{
    actionRef.current?.reloadAndRest?.();
    }

    // 选中树节点数据查询
    const handleSelect =async(record:any)=>{
      const selectKey = record[0];
      setKey(selectKey);
      const data = await getSelectTreeData(selectKey);
      // 页面联动值初始化
      if (data.riskExposureIsmini == '1') {
        setRiskFlag(true);
        closeAndRefresh();  
      } else {
        setRiskFlag(false);
      }
      if (data.riskExposureIsmini == '1') {
        setRiskWeightFlag(true);
      } else {
        setRiskWeightFlag(false);
      }
      formRef.current?.setFieldsValue(data);
    }

  // 风险暴漏分类规则删除
  const delRiskRule = async (record:any) => {
    baseFun.confirm('请确认是否继续操作',async() =>{
      await delRiskRuleData(record);
      closeAndRefresh();
    }) 
  }

  // 风险暴漏分类规则当前行查询
  const selectRiskRowData = async (record:any) => {
    const formDataList = await getRiskDataList(record,key);
    backformRef.current?.setFieldsValue(formDataList[0]);
  }

  // 编辑规则编号
  const setRuleNoAdd = () => {
    let lastEditRuleNo ="";
    if (formData !== null || formData !== undefined) {
      if (formData?.length == 0) {
        lastEditRuleNo = "FXBL" + key + 1;
      } else {
        let lastNo = formData?.filter((item)=>{
          return item.ruleNo == formData[formData.length-1].ruleNo;
        })[0].ruleNo;
        let numberNo = lastNo?.substring(lastNo.length-3,lastNo.length);
        let castnumber = toNumber(numberNo);
        castnumber = castnumber+1;
        lastEditRuleNo = "FXBL" + key + castnumber;
      }
    } else {
      lastEditRuleNo = "FXBL" + key + 1;
    }
    setEditRuleNo(lastEditRuleNo);
  }

    // 页面展示元素
    const columns: ProColumns<riskExposureClassRuleModel>[] = [
      {
        title: '计算实例号',
        dataIndex: 'calcindex',
        search: false,
        hideInTable: true,
      },
      {
        title: '起始数据日期',
        dataIndex: 'startDate',
        search: false,
        hideInTable: true,
      },
      {
        title: '截止数据日期',
        dataIndex: 'endDate',
        search: false,
        hideInTable: true,
      },
      {
        title: '规则编号', 
        dataIndex: 'ruleNo',
        search: false,
        hideInTable: false,
      },
      {
        title: '规则说明', 
        dataIndex: 'ruleName',
        search: false,
        hideInTable: false,
      },
      {
        title: '产品名称', 
        dataIndex: 'ruleProductNo',
        search: false,
        hideInTable: false,
        valueType: 'treeSelect',
          request: () => fetchDict('CUST_TYPE_LV02'),
          fieldProps: {
           treeDefaultExpandAll: true,
           treeCheckable:true,
        },
      },
      {
        title: '权重(%)', 
        dataIndex: 'riskExposureWeight',
        search: false,
        hideInTable: false,
      },
      {
        title: '输入数据源', 
        dataIndex: 'ruleIn',
        search: false,
        hideInTable: false,
        valueType: 'treeSelect',
        request: () => fetchDict('CUST_TYPE_LV02'),
        fieldProps: {
         treeDefaultExpandAll: true,
         treeCheckable:true,
      },
      },
      {
        title: '输出数据源', 
        dataIndex: 'ruleOut',
        search: false,
        hideInTable: false,
        valueType: 'treeSelect',
        request: () => fetchDict('CUST_TYPE_LV02'),
        fieldProps: {
         treeDefaultExpandAll: true,
         treeCheckable:true,
      },
      },
      {
        title: '执行序号', 
        dataIndex: 'ruleIndex',
        search: false,
        hideInTable: false,
      },
      {
        title: '风险暴露分类认定规则', 
        dataIndex: 'ruleGetdata',
        search: false,
        hideInTable: false,
      },
      {
        title: '操作',
        dataIndex: 'operate',
        valueType: 'option',
        render: (_, record) => [
          <SDOperate
            key="roleCfg"
            icon={<WomanOutlined />}
            successMessage=""
            onClick={
              ()=>{
              selectRiskRowData(record);
              setBackEditType('update');
              setDetailVisible(true);
              setCurrentRow(record);
             }}
          >
            修改
          </SDOperate>,
          <SDOperate
          key="roleCfg"
          icon={<WomanOutlined />}
          successMessage=""
          onClick={()=>{
            delRiskRule(record);
          } }
        >
          删除
        </SDOperate>,
         
        ],
      },

    ];

    // 右键菜单
    const items: any[] = [
      {
        label: <a>新建</a>,
        key: 'create',
      },
      {
        label: <a>作废</a>,
        key: 'delete',
      },
      {
        type: 'divider',
      },
    ];


    return(
        <SDPage footer={[<SDSubmitButton successMessage='' editType={editType}   formRef={formRef} doSubmit={handleSave} >保存</SDSubmitButton>]}> 
        <SDLayout subLayout='horizontal' >
        <SDLayout
         title='菜单列表'
         colSpan='25%'
         fixHeight
         >
         <DirectoryTree treeData={treeData} onSelect={handleSelect} showLine={true} autoExpandParent={true}  
         titleRender={(nodeData) => {
          return (
            <Dropdown menu={{ items, onClick: (e) => {
              console.log(e.key,nodeData)
              if (e.key == 'create') {
                   createNode(nodeData);
              } else if (e.key == 'delete') {
                   deleteNode(nodeData);
              }
            }}} trigger={['contextMenu']}
            >
              <span>{nodeData.title}</span>
            </Dropdown>
          )
         }}
         onRightClick={({event, node}: any) => {
          event.preventDefault();
         }}
         />
        </SDLayout>
        <SDLayout
         title='风险暴露分类信息维护'
         colSpan='75%'
         fixHeight
         >
        <SDForm 
            editType={editType}
            //doSubmit={handleSave}
            formRef={formRef}
            onValuesChange={
              (changedValues, values)=>{
                if (changedValues.riskExposureIsmini == '1'){
                  setRiskFlag(true);
                  setRiskWeightFlag(true);
                } else if (values.riskExposureIsmini == '0' || values.riskExposureIsmini== null) {
                  setRiskFlag(false);
                  setRiskWeightFlag(false);
                  formRef.current?.setFieldValue('riskExposureWeight',null);
                }
              }
            }
            >
            <SDFormText name="riskExposureNo" required={true} 
            bgValidater={(riskExposureNo: string) => isNotExist({
              riskExposureNo: riskExposureNo,
              calcIndex: '',
              startDate: '',
              endDate: '',
              term: '',
              dataDate: '',
              riskExposureName: '',
              riskExposureStageId: '',
              defaultOut: '',
              riskExposureIndex: '',
              riskExposureSuper: '',
              riskExposureSuperName: '',
              riskExposureIsmini: '',
              riskExposureWeight: '',
              riskExposureState: ''
            })}
            readonlyCond='update'  label="项目代码"/>
            <SDFormText name="riskExposureName" readonlyCond='update' required={true} label="项目名称" rules={[{max:50,message:'不可超过50个字'},]}/>
            <SDFormText name="riskExposureSuper"  label="上级项目代码"/>
            <SDFormText name="riskExposureSuperName"  label="上级项目名称"/>
            <SDFormDict name="riskExposureIsmini" dictKey="YESORNO" label="是否最细一级"/>
            {riskWeightFlag && <SDFormText name="riskExposureWeight" required={true}   label="默认权重(%)"/>}
            <SDFormDict name="defaultOut" dictKey='CUST_TYPE_LV02'  label="默认输出数据源"/>
            <SDFormDict name="riskExposureStageId" dictKey='CUST_TYPE_LV02' label="所属阶段"/>
            <SDFormText name="riskExposureIndex"  label="认定顺序号"/>
            <SDFormText name="riskExposureState" readonlyCond='both' label="状态"/>
        </SDForm>


        { riskFlag &&
        <SDTable
              title="风险暴露分类认定规则列表"
              search={false}
              rowKey="ruleNo"
              columns={columns}
              toolBarRender={(_, { selectedRows }) => [
                <SDButton
                  key="create"
                  icon={<PlusSquareTwoTone />}
                  successMessage=''
                  onClick={() => {
                    setDetailVisible(true);
                    setBackEditType('create');
                    setRuleNoAdd();
                  }}
                >
                  新建
                </SDButton>,
                ]}
              request={ async(record:riskExposureClassRuleModel)=>{
                const formDataList = await getRiskDataList(record,key);
                setFormData(formDataList);
                return {data:formDataList}
              }}
              actionRef={actionRef}
              formRef={proformRef}
              setDetailVisible={() => {setDetailVisible(true)}}
              setEditType={setBackEditType}
              setCurrentRow={setCurrentRow}
        />}

      {detailVisible && (
      <SDModalForm          
        title={'详细信息'}
        editType={backEditType}
        visible={detailVisible}
        initialValues={{ruleNo:editRuleNo}}
        onVisibleChange={() => {setDetailVisible(false)}}
        footer={[
        <SDSubmitButton  editType={backEditType}   formRef={backformRef} doSubmit={handleRiskRuleSave} >保存</SDSubmitButton>,
        <SDButton
          key="closeUpdate"
          successMessage=''
          onClick={() => {setDetailVisible(false);}}>关闭</SDButton>
        ]}
        formRef={backformRef}
      >
        <SDAreaTtile title='风险暴露分类认定规则信息'/>
          <SDFormText name="ruleNo" readonlyCond='both'  label="规则编号"/>
          <SDFormText name="ruleName" required={true}  label="规则说明"/>
          <SDFormDict name="ruleProductNo"  dictKey='CUST_TYPE_LV02' rules={[{required:true}]} label="产品名称"/>
          <SDFormText name="riskExposureWeight"  label="权重(%)"/>
          <SDFormDict name="ruleIn" dictKey='CUST_TYPE_LV02' rules={[{required:true}]} label="输入数据源"/>
          <SDFormDict name="ruleOut" dictKey='CUST_TYPE_LV02' rules={[{required:true}]} label="输出数据源" />
          <SDFormText name="ruleIndex" required={true}  label="执行序号" />
          <SDFormText name="ruleGetdata" required={true} type="textarea" label="风险暴露分类认定规则"/>
      </SDModalForm>
      )}
        </SDLayout>
        </SDLayout>
        </SDPage>

        
    )

  

}
export default info;