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

import { useState, useEffect } from 'react';
import {
  getTreeFileTableData,
  getSelfEvaluation,
  selfEvolutionCommit
} from '@/pages/GradeHospitalAccreditation/articleManagement/server';
import { delDetailRule } from '@/pages/GradeHospitalAccreditation/accreditationDetail/service';
import {getScoreLevelData} from '@/pages/PlatformMana/generalSetting/serve';

// ledgerUpload
const ledgerUpload = () => {
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [scoreList, setScoreList] = useState<any[]>([]);
  const [records, setRecords] = useState<MccsRecordList.MccsRecordListType>();
  const [currentRecord, setCurrentRecord] = useState<API.tableDataItemType>();
  const [currentLeafData, setCurrentLeafData] = useState<API.LeafDataType>();
  const [selfEvaluationRecords, setSelfEvaluationRecords] = useState<MccsRecordList.MccsRecordListType>([]); // 自评记录
  // const [drawerFormType, setDrawerFormType] = useState<'ARTICLE_SET' | 'BATCHSETTING'>(  'ARTICLE_SET');

  const [targetScores,setTargetScores] = useState<MccsClickableTabs.TabType[]>([]);  // 可选等级列表

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

  const [currentSelectedSelefEvolution,setCurrentSelectedSelefEvolution] = useState<{label: string,value: any}>(); // MccsClickableTabs 点击对象

  const getTableData = async () => {
    // 根据选中表格的id获取对应的详情
    if (currentRecord) {
      const resp = await getTreeFileTableData({
        id: currentRecord ? currentRecord.id : 0,
      });

      if (resp) {
        const { leafData, isLeaf } = resp;

        if (isLeaf && leafData) {
          setCurrentLeafData(leafData);
        }
      }
      return [];
    }
  };

  const delRuleHandle = async (id: number) => {
    await delDetailRule(id);
  };

  const getSelfEvaluationRecordList = async (id: number) => {
    // 获取自评记录（无法从accreditationDetail迁移）
    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 commitSelfEvolution = async ()=>{
    // 提交自评
    if(currentLeafData&&currentSelectedSelefEvolution){
      // 存在详情信息，且已选择评分
      const {id} = currentLeafData.reviewArticle;
      const _userData = localStorage.getItem('userData');
      if(_userData){
        const userData: {name: string,userId: number} = JSON.parse(_userData)
        const params = {
          id:Number(id),
          selfEvaluation:`${currentSelectedSelefEvolution || 'null'}`,
          userId:userData?.userId,
          userName:userData?.name
        }
         const resp = await selfEvolutionCommit(params);
         if(resp&&currentRecord){
           // 刷新自评记录
          getSelfEvaluationRecordList(Number(currentRecord.id));
          setSelectedSelfEvolution(undefined);  // 清空选中项
          setCurrentSelectedSelefEvolution(undefined);
         }
      }  
    }else{
      // notification['info']({
      //   message: '请选择评分！',
      // });
    }
  }

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

  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);
  }

  useEffect(() => {
    // 点击时获取对应详情
    getTableData();
    // getSelectableSelfScoreList();
  }, [currentRecord]);




  useEffect(() => {
    if (currentLeafData) {
      const {
        systemEvaluation,
        targetEvaluation,
        selfEvaluation,
      } = currentLeafData.reviewArticle;
      const tempScoreList = [
        {
          label: '自评',
          value: selfEvaluation || '-',
        },
        // {
        //   label: '现场查核',
        //   value: siteEvaluation ? siteEvaluation : '-',
        // },
        {
          label: '目标',
          value: targetEvaluation || '-',
        },
        {
          label: '系统评分',
          value: systemEvaluation || '-',
        },
      ];
      // console.log({tempScoreList});

      // const tempRecords = records.map((item: API.RecordsItemType) => {
      //   if (item.details) {
      //     const tempArr = item.details.map((val) => ({
      //       name: val.userName,
      //       fileName: val.fileName,
      //       fileUrl: val.fileUrl,
      //       createTime: val.createTime,
      //       recordTypeName: val.recordTypeName,
      //       historyRecords: [],
      //     }));
      //     return {
      //       evaluation: item.evaluation,
      //       details: tempArr,
      //     };
      //   }
      //   return { evaluation: 'null', details: [] };
      // });

      setScoreList(tempScoreList);
      // setRecords(tempRecords);
    }
  }, [currentLeafData]);

  return {
    drawerVisible,
    currentRecord,
    setCurrentRecord,
    setDrawerVisible,
    scoreList,
    records,
    delRuleHandle,
    currentLeafData,
    getSelfEvaluationRecordList,
    selfEvaluationRecords,
    setCurrentSelectedSelefEvolution,
    onSelfEvolutionTabChange,
    commitSelfEvolution,
    selectedSelfEvolution,
    targetScores,
    getTableData,
    getSelectableSelfScoreList
  };
};

export default ledgerUpload;
