
/*
 * @Author: your name
 * @Date: 2021-09-14 10:46:45
 * @LastEditTime: 2022-04-29 16:55:25
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /MedicalWisdomCheckSys/src/pages/GradeHospitalAccreditation/articleManagement/model.ts
 */


import { useState, useEffect } from 'react';
import {
  getTreeFileTableData,
  getDepartmentList,
  settingArticle,
  batchSettingArticle,
  getSelfEvaluation,
  selfEvolutionCommit,
  getUploadLedgerSelectableType,
  getCurrentHospSelfScore,
  getRuleChildrens,
  getTaizhangImplementation,
  commitTaizhangImplementation,
  commitTaizhangDataDirectoryTableList,
} from './server';
import { getTreeList, getMaterialListGrades } from '@/pages/GradeHospitalAccreditation/accreditationDetail/service';
import {
  getScoreLevelData,
  getAccreditationTypeData,
  getLedgerType
} from '@/pages/PlatformMana/generalSetting/serve';


import { notification } from 'antd';
import { DataItemType, MultiResponsibilitySelecterValueType } from './components/articleDetailModule/drawer/fragment/multi';

export interface ImplementationDataItem {
  level: string;
  note: string;
}

export type ImplementationDataItemCache = Record<string, ImplementationDataItem[]>;

// articleManagement
const articleManagement = () => {
  const [treeData, setTreeData] = useState<any[]>([]);
  const [currentActivedTree, setCurrentActivedTree] = useState<MccsFileTree.childTree>();
  const [isLeaf, setIsLeaf] = useState(false);
  const [scoreList, setScoreList] = useState<{ label: string; value: string }[]>([]);
  const [leafData, setLeafData] = useState<API.LeafDataType>(); // 叶子结点数据
  

  const [targetScores, setTargetScores] = useState<MccsClickableTabs.TabType[]>([]);
  const [ruleTypes, setRuleTypes] = useState<MccsClickableTabs.TabType[]>([]);

  const [selfEvaluationRecords, setSelfEvaluationRecords] = useState<MccsRecordList.MccsRecordListType>([]); // 自评记录
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[] | string[]>([]);

  const [drawerVisible, setDrawerVisible] = useState(false);

  /**
   * ARTICLE_SET 条文设置
   * BATCHSETTING 批量设置
   */

  const [drawerFormType, setDrawerFormType] = useState<'ARTICLE_SET' | 'BATCHSETTING'|'Ledger'|'VIEWLEDGER'|undefined>(undefined);

  const [reloadRightContent, setReloadRightContent] = useState(false);

  const [moduleMode, setModuleMode] = useState(false); // true台账上传 false条文管理

  const [modalVisible, setModalVisible] = useState(false);

  const [selectedSelfEvolution, setSelectedSelfEvolution] =
    useState<{ label: string; value: any }>(); // MccsClickableTabs value值

  const [currentSelectedSelefEvolution, setCurrentSelectedSelefEvolution] =
    useState<{ label: string; value: any }>(); // 当前选中自评 点击对象

  const [uploadLedgerTypeList, setUploadLedgerTypeList] = useState<MccsClickableTabs.TabType[]>([]); // 上传台账可选类型

  const [currentHospSelfScoreAndOthers, setCurrentHospSelfScoreAndOthers] = useState<string>(); // 当前医院评分及自评结果

  const [editMode, setEditMode] = useState(false); // 编辑模式，台帐上传页面用到

  const [implementationData, setImplementationData] = useState<ImplementationDataItemCache>({}); // 执行情况说明数据
  const [taizhangDataDirectoryCommitList, setTaizhangDataDirectoryCommitList] = useState<
    API.TaizhangDataDirectoryCommitListItem[]
  >([]);

  const [isShowMineOnly, setIsShowMineOnly] = useState(false); // 左侧树形结构是否只展示当前用户所属的

  const [hasEditAuthority, setHasEditAuthority] = useState(false); // 是否有编辑权限

  const [gradeOptions, setGradeOptions] = useState<{ label: string, value: string | number }[]>([]);
  const [accountTypeOptions, setAccountTypeOptions] = useState<{ label: string, value: string | number }[]>([]);
  const [articleSettingFormInit, setArticleSettingFormInit] = useState<{
    responsibilityDepartment:{label:string;value:any};
    responsibilityUser:{label:string;value:any};
    Co_DepartmentAndManager:MultiResponsibilitySelecterValueType[];
    targetScores:{label:string;value:any};
    articleType:{label:string;value:any};
    
  }|undefined>(undefined);  //条文设置表单回显默认值

  const [currentSelectedActObj, setCurrentSelectedActObj] = useState<any>(undefined);  //当前正在操作的对象，例如当前选中的树中层级数据，点击详情的的行数据

  const [detailDrawerVisible, setdetailDrawerVisible] = useState(false);   //条文详情抽屉

  const [ifHasEdit,setifHasEdit] = useState(false);   //是否操作了条文设置或者编辑操作
  
  //设置当前操作表格里的资料目录项
  const [currentActDataDireactory,set_currentActDataDireactory] = useState<API.TaizhangDirectoryTableItem|undefined>(undefined);




  const getArticleTreeData = async (keyword?: string | number) => {
    // 获取树数据
    const { list = [] } = await getTreeList(isShowMineOnly, keyword);
    setTreeData(list);
  };

  const getTableData = async (params?: any, sorter?: any, filter?: any) => {
    // 根据选中树结构的id获取对应的详情
    let specifyId: number | null = null;

    if (params && params.id) {
      // 当存在指定id
      specifyId = params.id;
    }

    if (currentActivedTree || specifyId) {
      const resp = await getTreeFileTableData(
        specifyId
          ? {
            // 传入树结构id指定获取某一节点对应数据
            pageSize: 10,
            ...params,
            id: specifyId,
          }
          : {
            // 直接拿树结构id
            pageSize: 10,
            ...params,
            id: currentActivedTree ? currentActivedTree.id : 0,
          },
        moduleMode,
      );

      if (resp) {
        const { page, leafData, isLeaf } = resp;
        setIsLeaf(isLeaf);
        if (!isLeaf && page) {
          // 非叶子结点返回table数据
          const { list = [], totalCount } = page;
          return {
            data: list,
            success: true,
            total: totalCount,
          };
        }
        setLeafData(undefined);
        if (isLeaf && leafData) {
          setLeafData(leafData);
        } else {
          setLeafData({
            reviewArticle: {
              id: -1,
              ruleId: -1,
              numStr: '',
              version: '',
              selfEvaluation: '',
              targetEvaluation: '',
              systemEvaluation: '',
              siteEvaluation: '',
              responsibilityDepartmentId: -1,
              responsibilityDepartmentName: '-',
              responsibilityUserId: -1,
              responsibilityUserName: '-',
              accountType: '-',
              hospId: -1,
              userId: -1,
              userIds:[],
              pfmReviewArticleDepartList:[]
            },
            pfmViewRuleDetailDataVoList: [],
            pfmImplementations: [],
          });
        }
      }
      return [];
    }
  };

  const getDepartmentRequest = async () => {
    // 获取单位列表
    const resp = await getDepartmentList();
    if (resp) {
      const { list = [] } = resp;
      return list.map((item: any) => ({
        label: item.name,
        value: item.id,
      }));
    }
    return [];

  };

  type FormValueType = {
    articleType: { label: string; value: any };

    Co_DepartmentAndManager:DataItemType[];
    main_DepartmentAndManager:DataItemType[];

    targetScores: { label: string; value: any };
  };

  const batchSetting = async (values: FormValueType) => {
    // 批量设置
    const {main_DepartmentAndManager,Co_DepartmentAndManager} = values;
    
    if(main_DepartmentAndManager[0]){
      const resp = await batchSettingArticle({
        ruleIds: selectedRowKeys,
        responsibilityDepartmentId: main_DepartmentAndManager[0].responsibilityDepartment.value,
        responsibilityDepartmentName: main_DepartmentAndManager[0].responsibilityDepartment.label,
        responsibilityUserId: main_DepartmentAndManager[0].responsibilityUser.value,
        responsibilityUserName:main_DepartmentAndManager[0].responsibilityUser.label,
        targetEvaluation: values.targetScores.value,
        articleType: values.articleType.value,
        responsibilityList:Co_DepartmentAndManager.map(t=>({
          responsibilityDepartmentId: t.responsibilityDepartment.value,
          responsibilityDepartmentName: t.responsibilityDepartment.label,
          responsibilityUserId: t.responsibilityUser.value,
          responsibilityUserName:t.responsibilityUser.label,
        }))
      });
  
      if (resp) {
    
        setReloadRightContent(true);
  
        return true;
      }
    }
    
  };

  const setArticle = async (values: FormValueType) => {
    // 条文设置

    setifHasEdit(true);

    if (currentActivedTree && leafData) {

      let ruleId = 0;
      if (detailDrawerVisible) {
        //在条文抽屉详情里条文设置
        ruleId = currentSelectedActObj.id;
      } else {
        //正常在详情页设置条文
        ruleId = Number(currentActivedTree.id)
      }

      const { id } = leafData.reviewArticle;

      const {main_DepartmentAndManager,Co_DepartmentAndManager} = values;

      const paramsData = {
        id,
        ruleId: ruleId,
        responsibilityDepartmentId: main_DepartmentAndManager[0].responsibilityDepartment.value,
        responsibilityDepartmentName: main_DepartmentAndManager[0].responsibilityDepartment.label,
        responsibilityUserId: main_DepartmentAndManager[0].responsibilityUser.value,
        responsibilityUserName:main_DepartmentAndManager[0].responsibilityUser.label,
        targetEvaluation: values.targetScores.value,
        articleType: values.articleType.value,
        responsibilityList:Co_DepartmentAndManager.map(t=>({
          responsibilityDepartmentId: t.responsibilityDepartment.value,
          responsibilityDepartmentName: t.responsibilityDepartment.label,
          responsibilityUserId: t.responsibilityUser.value,
          responsibilityUserName:t.responsibilityUser.label,
        }))
      };

      const resp = await settingArticle(paramsData);
      if (resp) {
        // 更新界面信息
        if (detailDrawerVisible) {
          //当条文详情抽屉存在时，暂不刷新table，交给抽屉关闭时判断刷新,只刷新详情数据
          getTableData({id:currentSelectedActObj.id});
    
        }else{
          getTableData();
        }
        
        setDrawerVisible(false);
      }
    }
  };

  

  const getSelfEvaluationRecordList = async (id: number) => {
    const resp = await getSelfEvaluation(id);

    if (resp) {
      const { list }: { list: API.GetSelfEvaluationRequestType } = resp;
      const tempArr = list.map((t) => ({
        evaluation: t.selfEvaluation,
        details: [
          {
            name: t.userName,
            fileName: t.selfEvaluation,
            fileUrl: '',
            historyRecords: [],
            // recordTypeName:t.selfEvaluation,
            createTime: t.createDate,
          },
        ],
      }));
      setSelfEvaluationRecords(tempArr);
    }
  };

 

  const compalier = (data: ImplementationDataItem[], base: any[]) => {
    const result: ImplementationDataItem[] = [];

    const hasDataKeys = data.map((item) => item.level); // 找出已经请求到数据的集合

    const difference = hasDataKeys
      .concat(base)
      .filter((v) => !hasDataKeys.includes(v) || !base.includes(v)); // 找出缺失的项
    // console.log({difference});
    const needAddImplementationData = difference.map((item) => ({ level: item, note: '' }));
    const lastimplementationData = [...data, ...needAddImplementationData]; // 将需要新增的项添加
    lastimplementationData.forEach((item) => {
      // 数据排序，A>B>C
      switch (item.level) {
        case 'A':
          result[2] = item;
          break;
        case 'B':
          result[1] = item;
          break;
        case 'C':
          result[0] = item;
          break;
      }
    });
    return result;
  };

  const implementationDataFilter = (data: ImplementationDataItem[]) => {
    if (editMode && moduleMode) {
      if (selectedSelfEvolution?.label == 'A') {
        /**
         * 根据业务逻辑，当选中的值为A时，需要提供A，B，C三个的数据，若没有则需要添加
         */
        if (data.length == 3) return data; // 存在三个值时，直接返回
        return compalier(data, ['A', 'B', 'C']);
      }

      if (selectedSelfEvolution?.label == 'B') {
        /**
         * 根据业务逻辑，当选中的值为B时，需要提供B,C两个的数据，若没有则需要添加
         */
        if (data.length == 2) return data; // 存在2个值时，直接返回
        return compalier(data, ['B', 'C']);
      }
      if (selectedSelfEvolution?.label == 'C') {
        /**
         * 根据业务逻辑，当选中的值为C时，需要提供C一个个的数据，若没有则需要添加
         */
        if (data.length == 1) return data; // 存在1个值时，直接返回
        return compalier(data, ['C']);
      }
    }
    return data;
  };

  const getImplementationForEdit = async ({
    numStr,
    version,
    level,
  }: {
    numStr: string;
    version: string;
    level: string;
  }) => {
    // 或区指定等级的执行情况说明数据，同时根据返回的数据自行添加需要补充的项
    if (implementationData[level]) return; // implementationData集合里已经有了该等级对应的数据时，不请求，为了保证编辑的数据缓存

    const data = await getTaizhangImplementation({ numStr, version, level });

    const implementData: ImplementationDataItem[] = data.map((item) => ({
      level: item.level,
      note: item.note,
    }));
    const resultData = implementationDataFilter(implementData); // 得到改造过的数据
    /**
     * 
     * 应业务要求，自评等级切换时保留之前填写数据
     * 所以额外建立一个键值对象进行缓存
     */

    setImplementationData({ ...implementationData, [level]: resultData });
  };

  const onSelfEvolutionTabChange = (value: { label: string; value: any }) => {
    // 自评tab切换回调
    value && setCurrentSelectedSelefEvolution(value);
    value && setSelectedSelfEvolution(value);
  };

  const commitSelfEvolution = async () => {
    // 提交自评
    if (leafData && currentSelectedSelefEvolution) {
      // 存在详情信息，且已选择评分
      const { id } = leafData.reviewArticle;
      const _userData = localStorage.getItem('userData');
      if (_userData) {
        const userData: { name: string; userId: number } = JSON.parse(_userData);
        const params = {
          id: Number(id),
          selfEvaluation: `${currentSelectedSelefEvolution ? currentSelectedSelefEvolution.value : 'null'
            }`,
          userId: userData?.userId,
          userName: userData?.name,
        };
        const resp = await selfEvolutionCommit(params);
        if (resp && currentActivedTree) {
          // 刷新自评记录
          getSelfEvaluationRecordList(Number(currentActivedTree.id));
          setSelectedSelfEvolution({ label: 'null', value: 'null' }); // 清空选中项
          setCurrentSelectedSelefEvolution(undefined);
        }
      }
    } else {
      notification.info({
        message: '请选择评分！',
      });
    }
  };



  const getScoreList = async () => {
    // 条文评级
    const data = await getScoreLevelData();
    const tempArr = data.map((t: any) => ({
      label: t.levelNumber,
      value: t.levelNumber,
      configStatus: t.configStatus,
    }));
    return Promise.resolve(tempArr);
  };

  const accreditationGroupType = async () => {
    // 获取条文组别
    const data = await getAccreditationTypeData();
    const tempArr = data.map((t: any) => ({ label: t.categoryType, value: t.categoryType }));
    return Promise.resolve(tempArr);
  };

  const getUploadLedgerType = async () => {
    // 台账类型
    const data = await getUploadLedgerSelectableType();
    if (data) {
      const tempArr = data.map((t: API.RuleChildsItemType) => {
        const tempList = t.generalNameList.map((a) => {
          return {
            label: a.generalName,
            value: a.id,
          };
        });
        return { label: t.levelNumber, list: tempList };
      });
      return Promise.resolve(tempArr);
    }
  };

  const getCurrentHospScore = async () => {
    // 获取医院评分及自评信息
    const resp = await getCurrentHospSelfScore();
    setCurrentHospSelfScoreAndOthers(resp);
  };

  const getSelectableSelfScoreList = async () => {
    // 获取自评可选列表
    const resp = await getScoreLevelData();
    const listFilted = resp.filter((t: any) => t.configStatus != 0);
    const list = listFilted.map((t: any) => ({ label: t.levelNumber, value: t.levelNumber }));
    setTargetScores(list.reverse());
  };

  const getSelectableRuleChilds = async (id: number) => {
    // 获取台账上传时可选下拉类型
    const resp = await getRuleChildrens(id);
    return resp.map((t: { id: number; name: string }) => ({ label: t.name, value: t.id }));
  };

  const commitTaizhangImplementationHandle = async () => {
    // console.log({taizhangDataDirectoryCommitList});
    if (leafData) {
      const selfEvo = selectedSelfEvolution ? selectedSelfEvolution.label : '';
      const list = implementationData[selfEvo].map((item) => ({
        selfEvaluation: item.level,
        node: item.note,
      }));
      // 提交台账执行情况说明
      const respImplementation = await commitTaizhangImplementation({
        hospId: `${leafData.reviewArticle.hospId}`,
        id: leafData.reviewArticle.id,
        numStr: leafData.reviewArticle.numStr,
        selfEvaluation: selfEvo,
        version: leafData.reviewArticle.version,
        implementationDtoList: list,
      });

      const respDataDirectoryTable = await commitTaizhangDataDirectoryTableList(
        taizhangDataDirectoryCommitList,
      );

      setEditMode(false);
      // console.log({respDataDirectoryTable,respImplementation})
      if (respDataDirectoryTable && respImplementation) {
        // 每次服务保存数据成功后，清空台账上传的缓存数据
        setImplementationData({}); // 清空执行情况说明
        setTaizhangDataDirectoryCommitList([]); // 清空台账上传资料目录

        getTableData(); // 两个保存都成功时刷新数据
      }
    }
  };


  const getGradeOptions = async () => {
    if (leafData) {
      const { numStr, version } = leafData.reviewArticle;
      const resp = await getMaterialListGrades({ numStr, version });
      if (resp) {
        const options = resp.map(item => ({ label: item.grade, value: item.grade }));
        setGradeOptions(options);
      }
    }
  }

  const getAccoutTypeOptions = async () => {
    const resp = await getLedgerType();
    if (resp) {
      const options = resp.map(item => ({ label: item.generalName, value: item.generalName }));
      setAccountTypeOptions(options);
    }
  }

  useEffect(()=>{
  
       if(!detailDrawerVisible&&ifHasEdit){
            //详情抽屉关闭时刷新table
            setReloadRightContent(true);
            //更新完数据，重置状态
            setifHasEdit(false);
       }

  },[detailDrawerVisible])

  useEffect(() => {
    if (!drawerVisible) {
      setDrawerFormType(undefined);
    }
  }, [drawerVisible]);

  useEffect(() => {
    // 叶子结点数据变化后相关回调
    if (leafData) {
      const { systemEvaluation, targetEvaluation, selfEvaluation, userId,userIds} =
        leafData.reviewArticle;

      const tempScoreList = [
        {
          label: '目标',
          value: targetEvaluation || '-',
        },
        {
          label: '自评',
          value: selfEvaluation || '-',
        },
        {
          label: '系统评分',
          value: systemEvaluation || '-',
        },
      ];
      /**
       * 默认加载页面时执行获取执行情况说明数据
       */
      const t = localStorage.getItem('userData') ? localStorage.getItem('userData') : '';
      const userData = JSON.parse(t as string);
      const valIndex = userIds.findIndex(t=>t == userData.userId)
      setHasEditAuthority(valIndex != -1);  //设置编辑权限
      // setHasEditAuthority(true);
      setImplementationData({ [selfEvaluation]: leafData.pfmImplementations });

      const selfEvolution = leafData.reviewArticle.selfEvaluation;
      setSelectedSelfEvolution({ label: selfEvolution, value: selfEvolution });
      setScoreList(tempScoreList);
      getSelectableSelfScoreList();
    }
  }, [leafData]);

  useEffect(() => {
    // 当抽屉类型改变时
    if (drawerFormType == 'BATCHSETTING' || drawerFormType == 'ARTICLE_SET') {
      getScoreList().then((data) => {
        const dataFilted = data.filter((t: any) => t.configStatus != 0); // 去掉不启动
        setTargetScores(dataFilted);
      });


      accreditationGroupType().then((data) => {
        setRuleTypes(data);
      });
    }
  }, [drawerFormType]);


  useEffect(() => {
    // 左侧树结构只看我的开关切换时，重新获取树结构数据
    getArticleTreeData();
  }, [isShowMineOnly]);

  useEffect(() => {
    // console.log({ leafData, selectedSelfEvolution });
    if (leafData && selectedSelfEvolution) {
      // 更新台账页面编辑下的执行情况说明
      getImplementationForEdit({
        level: selectedSelfEvolution.label,
        /**
         * 不能拿currentActivedTree里的version，numStr，
         * 因为台账上传页面详情抽屉读不到准确的四码和版本
         */
        version: leafData?.reviewArticle.version,
        numStr: leafData?.reviewArticle.numStr,
      });
    }
  }, [selectedSelfEvolution]);

  useEffect(() => {
    if (!editMode && leafData) {
      // 取消编辑时，将原自评等级设为默认
      const selfEvolution = leafData.reviewArticle.selfEvaluation;
      setSelectedSelfEvolution({ label: selfEvolution, value: selfEvolution });
    }

     //获取可选的等级
     getGradeOptions();
     //获取可选类型
     getAccoutTypeOptions();
     
  }, [editMode]);

  useEffect(() => {
    // 切换页面类型时做相关处理，如清除之前页面的默认数据
    if (!moduleMode) {
      setEditMode(false); // 条文管理界面无需编辑
      setIsShowMineOnly(false); // 条文管理界面关闭
    }
  }, [moduleMode]);

  return {
    isLeaf,
    treeData,
    setTreeData,
    getArticleTreeData,
    getTableData,
    currentActivedTree,
    setCurrentActivedTree,
    scoreList, // 评分
    getDepartmentRequest,
    targetScores,
    ruleTypes,
    leafData,
    setArticle,
    batchSetting,
    drawerFormType,
    setDrawerFormType,
    drawerVisible,
    setDrawerVisible,
    setSelectedRowKeys,
    reloadRightContent,
    setReloadRightContent,
    setModuleMode,
    moduleMode,
    selfEvaluationRecords,
    modalVisible,
    setModalVisible,

    onSelfEvolutionTabChange,
    commitSelfEvolution,
    selectedSelfEvolution,
    getSelfEvaluationRecordList,

    getUploadLedgerType,
    uploadLedgerTypeList,
    setUploadLedgerTypeList,
    currentHospSelfScoreAndOthers,
    getCurrentHospScore,
    getSelectableRuleChilds,
    editMode,
    setEditMode,

    implementationData,
    setImplementationData,
    commitTaizhangImplementationHandle,
    taizhangDataDirectoryCommitList,
    setTaizhangDataDirectoryCommitList,
    setIsShowMineOnly,
    isShowMineOnly,
    setSelectedSelfEvolution,
    hasEditAuthority,
    gradeOptions,
    accountTypeOptions,
    getGradeOptions,
    getAccoutTypeOptions,
    articleSettingFormInit, setArticleSettingFormInit,
    setCurrentSelectedActObj,
    currentSelectedActObj,
    detailDrawerVisible,
    setdetailDrawerVisible,
    currentActDataDireactory,
    set_currentActDataDireactory
  };
};

export default articleManagement;
