/* eslint-disable react/no-array-index-key */
/*
 * @Author: your name
 * @Date: 2021-09-06 09:07:56
 * @LastEditTime: 2022-06-06 10:37:56
 * @LastEditors: code4eat awesomedema@gmail.com
 * @Description: In User Settings Edit
 * @FilePath: /MedicalWisdomCheckSys/src/pages/GradeHospitalAccreditation/accreditationDetail/index.tsx
 */




import React, { useState, useEffect, useRef } from 'react'
import { Divider } from 'antd'
import MccsProFormText from '@/components/antdProOverwrite/MccsProFormText/index';
import { MccsModalContext, MccsModal } from '@/components/MccsModal/index';
import MccsPageContainer from '@/components/MccsPageContainer/index'
import MccsProCard from '@/components/MccsProCard/index';
import MccsFileTree from '@/components/MccsFileTree/index';
import { useModel } from 'umi';
import ProForm, { ProFormText, ProFormTextArea } from '@ant-design/pro-form';

import FormList from './components/FormList/index';
import MaterialTable from './components/materialTable/index';
import MccsSelect from '@/components/MccsProFormSelect/index';

import { getMaterialListGrades, getMaterialList, getMaterialDirList, addMaterialDirList, delMaterialDirList,editMaterialDirList } from './service';

import './index.less';




type AccreditationDetailProps = {

};



type treeItem = {
  title: string,
  id: string,
  code: string,
  isLeaf: boolean,
  children?: treeItem[],
  [propName: string]: any
}

type ruleList = {
  title: string,
  id: string,
  code: string,
}[]





const AccreditationDetail: React.FunctionComponent<AccreditationDetailProps> = props => {

  const { accreditationDetail } = useModel('allModels');
  const { getTreeData, treeData, delDetailRuleHandle, addDetailRuleHandle, editDetailRulehandle, detailRuleList, getDetailRuleListHandle, setDetailRuleList, ...restAccreditationModel } = accreditationDetail;


  const [mode, setMode] = useState(1); // 1,2
  const [currentActived, setCurrentActived] = useState<API.ResultTreeDataItem | treeItem>();

  const [isLeaf, setIsLeaf] = useState(false);
  const [childRuleList, setChildRuleList] = useState<ruleList>([]);

  const [modalVisible, setModalVisible] = useState(false);
  const [actionType, setActionType] = useState('add');
  const formListRef = useRef<FormList.FormListRefCurrent>(null);

  const [formDefaultData, setFormDefaultData] = useState<any>(undefined);
  const [defaultOpened, setDefaultOpened] = useState<string>();

  const [selectOptions, setSelectOptions] = useState<{ label: string, value: string }[]>([]); // 资料目录表格下拉筛选

  const [showCardThree, setShowCardThree] = useState(false);  // 是否展示资料目录栏
  const [materialDirModalVisible, setMaterialDirModalVisible] = useState(false); // 资料目录弹窗展示/掩藏
  const [allMaterialDirList, setAllMaterialDirList] = useState<{ label: string, value: string }[]>([]); // 所有可选的资料目录
  const [editMaterialDir,setEditMaterialDir] = useState(false); // 是否编辑资料目录数据
  const [currentEditMaterialDir,setCurrentEditMaterialDir] = useState<API.MaterialDirListItem>(); // 当前编辑的资料目录项数据
  const [reloadMaterialDirData,setReloadMaterialDirData] = useState(false);  // 是否刷新资料目录数据

  const onSelectHandle = (data: treeItem) => {

    setCurrentActived(data);  // 设置当前树数据
    const { isLeaf, children, id, code, version = 'ZJ201901' } = data;

    if (isLeaf) {
      // 叶子结点
      setIsLeaf(true);
      getDetailRuleListHandle(id);
      // 获取四码对应所有档次
      getMaterialListGradesFunc(code, version);
      setMode(2);
      setShowCardThree(true);
      // 每次切换叶子节点刷新资料目录表格数据
      setReloadMaterialDirData(true);

    } else {
      // 文件夹结点
      setMode(1);
      setIsLeaf(false);
      setShowCardThree(false);
      const tempArr = children ? children.map((item) => ({
        title: item.title,
        code: item.code,
        id: item.id,
      })) : [];
      setChildRuleList(tempArr);
    }
  }
  // 操作回调
  const actionHandle = ({ type, data }: { type: string, data: treeItem | null }) => {

    data ? setCurrentActived(data) : setCurrentActived(undefined);  // 点击获取当前树数据

    if (type == 'del') {
      // 删除
      setActionType('del');
      if (data) {
        const { id } = data;
        delDetailRuleHandle(id);
      }

    }
    if (type == 'edit') {
      setActionType('edit');
      data && setFormDefaultData(data);
      setModalVisible(true);
    }
    if (type == 'add') {
      setDetailRuleList([]);
      setActionType('add');
      setModalVisible(true);
    }
  }
  // 左侧树搜索回调
  const searchHandle = (val: any) => {
    getTreeData(val);
  }

  // 获取该四码所有档次
  const getMaterialListGradesFunc = async (code: string, version: string) => {
    const gadeList = await getMaterialListGrades({ numStr: code, version });
    if (gadeList) {
      const grades = gadeList.map(t => ({ label: t.grade, value: t.grade }));
      setSelectOptions(grades);
    }
  }

  // 获取叶子节点下资料目录表格数据
  const getMaterialListFunc = async (params: MaterialTable.GeDataParams) => {
    const { selectorFilter, keyword,pageSize=10,current } = params;
    if (currentActived) {
      const { code, version } = currentActived;
      const resp = await getMaterialList({
        grade: selectorFilter,
        keyword,
        numStr: code,
        version,
        pageSize,
        current
      });
      if (resp) {
        return {
            total:resp.totalCount,
            pageSize:resp.pageSize,
            list:resp.list,
            current:resp.current
        };
      } 
    } 
  }

  const getMaterialDirListFunc = async () => {
    // 获取所有资料目录集合用于弹窗表单
    if (currentActived) {
      const { code, version } = currentActived;
      const resp = await getMaterialDirList({ numStr: code, version });
      if (resp) {
        setAllMaterialDirList(resp.map(t=>({label:t,value:t})));
      }
    }
  }

  const addMaterialDirHandle = () => {
    // 新增资料目录数据
    setEditMaterialDir(false);
    setMaterialDirModalVisible(true);
  }

  const onMaterialDirModalVisibleChange = (bool: boolean) => {
    bool&&getMaterialDirListFunc();
    setMaterialDirModalVisible(bool);
  }

  type mateialDirModalValues = {
    grade: string[],
    note: string,
    directory: string,
    profileName: string,

  }
  // 资料目录弹窗表单提交
  const mateialDirModalFinishHandle = async (values: mateialDirModalValues) => {
    console.log('commit', values);
    const { grade, ...restVals } = values;
    if(editMaterialDir&&currentEditMaterialDir){
      // 编辑
      const resp = await editMaterialDirList({
        grade: grade.join(','),
        id:currentEditMaterialDir.id,
        directory:restVals.directory,
        note:restVals.note,
        profileName:restVals.profileName
      });
      if (resp) {
        setReloadMaterialDirData(true);
        return true;
      }
    }else{
      // 新增
      if (currentActived) {
        const { code, version, id } = currentActived;
        const resp = await addMaterialDirList({
          numStr: code,
          version,
          ruleId: id,
          grade: grade.join(','),
          ...restVals
        });
        if (resp) {
          setReloadMaterialDirData(true);
          return true;
        }
      }
    }
    
  }

  // 资料目录表格删除/编辑回调
  const tableItemActionHandle = async (type: 'DEL' | "EDIT", data: API.MaterialDirListItem[]) => {
    if (type == 'DEL') {
      if (await delMaterialDirList(data.map(t=>t.id))) {
        return true
      } 
        return false
      
    }

    if (type == 'EDIT') {
      setCurrentEditMaterialDir(data[0]);
      setEditMaterialDir(true);
      setMaterialDirModalVisible(true);
    }
    return null;
  }


  const FormNode = ({ visible }: { visible: boolean }) => {


    const [showMore, setShowMore] = useState(false);
    const [list, setList] = useState<API.RuleDetailListItem[]>([]);  //
    const [selecterList, setSelecterList] = useState<FormList.SelecterItem[]>([]);


    const formNodeSubmitHandle = (values: any) => {

      const { name, numStr } = values;
      let parentId = 0;
      if (currentActived) {
        const { id } = currentActived;
        parentId = Number(id);
      }

      if (actionType == 'add') {

        let details: any = [];
        const { levelNum = 0 } = currentActived || {};
        if (formListRef.current && levelNum == 3) {
          // 当是新增叶子结点，也就是增加第4层
          setShowMore(true);
          const tempArr = formListRef.current.getData();
          details = tempArr.map(item => {
            const { list, evaluation } = item;
            const tempList = list.map(val => ({ title: val.detail }));
            return {
              evaluation,
              detail: tempList
            }
          })

        }
        const paramData = {
          parentId,
          name,
          numStr,
          detail: details
        }
        addDetailRuleHandle(paramData);
      }

      if (actionType == 'edit') {

        if (currentActived) {
          const { id, isLeaf } = currentActived;
          let details: any = [];
          if (formListRef.current && isLeaf) {
            // 当是叶子结点
            const tempArr = formListRef.current.getData();
            // console.log({tempArr});
            details = tempArr.map(item => {
              const { list, evaluation } = item;
              const tempList = list.map(val => ({ title: val.detail }));
              return {
                evaluation,
                detail: tempList
              }
            })

          }
          const paramData = {
            id: Number(id),
            name,
            detail: isLeaf ? details : [],
          }
          editDetailRulehandle(paramData);
        }
      }
      setModalVisible(false);
      return true;
    }

    const formNodeVisibleHandle = (bool: boolean) => {

      setModalVisible(bool);
    }


    useEffect(() => {
  
      if (currentActived) {

        const { isLeaf, levelNum } = currentActived;
  
        isLeaf&&setReloadMaterialDirData(true); // 点击叶子结点，刷新资料目录数据
        isLeaf && setShowMore(true);// 当新增或编辑第4层时也就是叶子节点，增加表单数据
        (levelNum == 3 && actionType == 'add') && setShowMore(true);  // 当新增或编辑第4层时也就是叶子节点，增加表单数据

        if (isLeaf || (levelNum == 3 && actionType == 'add')) {
          // 展示子集时才请求
          restAccreditationModel.getScoreSelectableList().then(data => {
            const tempArrFilted = data.filter((t: any) => t.configStatus != 0);
            const tempArr = tempArrFilted.map((t: any) => ({ label: t.levelNumber, value: t.levelNumber }));
            setSelecterList(tempArr);
          })
        }

      }
    }, [currentActived]);



    useEffect(() => {
      setList(detailRuleList);
    }, []);


    return (
      <MccsModal title={actionType == 'edit' ? '编辑评审细则' : '新增评审细则'} visible={visible} onVisibleChange={formNodeVisibleHandle}
        initialValues={actionType == 'edit' ? { ...formDefaultData, name: formDefaultData.title, numStr: formDefaultData.code } : {}}
        onFinish={formNodeSubmitHandle}
      >
        {
          actionType == 'add' && (
            <MccsProFormText
              width="md"
              name="numStr"
              label="四码"
              placeholder="请输入名称"
            />
          )
        }
        <MccsProFormText
          width="lg"
          name="name"
          label="内容"
          type='textArea'
          placeholder="请输入名称"
        />
        {
          showMore && (
            <ProForm.Item
              label="等级明细"
              name="dataSource"
              // initialValue={defaultData}
              trigger="onValuesChange"
            >
              <FormList data={list} selecterList={selecterList} ref={formListRef} formContext={MccsModalContext} />
            </ProForm.Item>
          )
        }
      </MccsModal>
    )
  }


  useEffect(() => {
    if (treeData.length > 0) {
      // 默认展开书结构第一个结点
      const { id } = treeData[0];
      setDefaultOpened(`${id}`);
    }
  }, [treeData]);

  useEffect(() => {

  }, [currentActived]);

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


  return (
    <MccsPageContainer>

      {modalVisible && <FormNode visible={modalVisible} />}

      {
        /**
         * 新增编辑弹窗
         */
      }
      <MccsModal
        title={editMaterialDir?`编辑资料目录`:'新增资料目录'} visible={materialDirModalVisible}
        onVisibleChange={onMaterialDirModalVisibleChange}
        width={600} layout={'horizontal'} labelCol={{ span: 4 }}
        initialValues={editMaterialDir?{...currentEditMaterialDir,grade:currentEditMaterialDir?.grade.split(',')}:{}}
        onFinish={mateialDirModalFinishHandle}
      >
        <MccsSelect
          selectList={selectOptions ? [...selectOptions] : []}
          width="sm"
          fieldProps={{
            mode: 'multiple',
          }}
          name='grade'
          label='档次'
        />
        <MccsSelect
          showSearch
          withInput={true}
          selectList={allMaterialDirList}
          width="sm"
          name='directory'
          label='目录'
        />
        <ProFormText width="sm" name="profileName" label="资料名称" placeholder="请输入名称" />
        <ProFormTextArea
          name="note"
          label="备注"
          placeholder="请输入"
        />
      </MccsModal>

      <MccsProCard gutter={16} ghost direction='row'>
        <MccsProCard colSpan={8} style={{ height: '78vh' }} bodyStyle={{ padding: '16px' }}>
          {
            defaultOpened && (
              <MccsFileTree
                treeData={treeData}
                defaultSelected={defaultOpened}
                onSelectHandle={onSelectHandle}
                actionHandle={actionHandle}
                searchHandle={searchHandle}
                editable={true}
              />
            )
          }
        </MccsProCard>
        <MccsProCard colSpan={16} className='rightCard' style={{ height: '100%', overflow: 'hidden' }} >
          <div className="detailRuleTitle">{`${currentActived?.code} ${currentActived?.title}`}</div>
          <Divider />
          <div className="ruleDetailContainer">
            {
              mode == 1 && (
                <>
                  {
                    childRuleList.map((item) => {
                      return (
                        <div className='ruleList' key={item.id}>
                          <span className='code'>{item.code}</span>
                          <div className='ruleTitle'>{item.title}</div>
                        </div>
                      )
                    })
                  }
                </>
              )
            }
            {
              mode == 2 && (
                <>

                  {
                    detailRuleList.map((item, index) => {
                      return (
                        <div className='scoreList' key={index}>
                          <div className='score'>
                            <span className='scoreVal'>{`${item.evaluation}：`}</span>
                            <span className='scoreSub'>{`符合“${item.evaluation}”并具备以下要求`}</span>
                          </div>
                          <div className='scoreCondition' >
                            {
                              item.detail.map((val, i) => {
                                return (
                                  <div key={i}>{val.title}</div>
                                )
                              })
                            }
                          </div>
                        </div>
                      )
                    })
                  }

                </>
              )
            }
          </div>
        </MccsProCard>
      </MccsProCard>
    </MccsPageContainer>
  );
};

export default AccreditationDetail