// 审核进度组件
import React, { useEffect, useRef, useState } from "react";
import { connect } from "umi";
import type { ConnectState } from "@/models/connect";
import { Card, Drawer, FormInstance, Steps, Tooltip } from "antd";
import { handleGetGetBUSINESSAPPROVALDetail } from "@/pages/reports/ShopExpenseDetail/service";
import './ReviewProcess.less'
import { handleGetAPPROVALROUTEList } from "@/pages/Setting/serviceConfig/service";
import ProTable, { ActionType } from "@ant-design/pro-table";
import moment from 'moment'
import { getFractionalPart } from "@/services/options";
import { handleGetAPPLYAPPROVEList } from "./service";

const { Step } = Steps
// changeDesc  是默认把之前的发起申请的备注 返回到表单里面 changeDesc是一个表单的formRef
const ReviewProcess: React.FC<{ showReviewProcess: boolean, compareCurrent?: any, type?: string, OPERATION_TYPES?: number, changeDesc?: any, inItiate?: boolean }> = (props) => {
  const { showReviewProcess } = props
  const { compareCurrent } = props
  const { type } = props
  const { OPERATION_TYPES } = props
  const { changeDesc } = props
  const { inItiate } = props // 判断是不是在开票的审核中
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  // 流程进度的数组
  const [progressList, setProgressList] = useState<any>()
  // 进度流畅的详情信息
  const [progressDetail, setProgressDetail] = useState<any>()
  // 当前这步是第几个
  const [currentSort, setCurrentSort] = useState<number>(0)
  // 流程详情抽屉
  const [showProcessDrawer, setShowProcessDrawer] = useState<boolean>(false)
  // 用来在表格里面处理数据 输出表格数据
  const [defaultTableData, setDefaultTableData] = useState<any>()
  // 第一个状态取出来展示数据
  const [firstStepDetail, setFirstStepDetail] = useState<any>()

  const columns: any = [
    {
      title: '环节名称',
      width: 250,
      ellipsis: true,
      dataIndex: 'APPLYAPPROVE_NAME',
      hideInSearch: true
    },
    {
      title: '经办人',
      width: 250,
      ellipsis: true,
      dataIndex: 'STAFF_NAME',
      hideInSearch: true
    },
    {
      title: '审核意见/驳回意见',
      width: 450,
      ellipsis: true,
      dataIndex: 'APPLYAPPROVE_INFO',
      hideInSearch: true
    },
    {
      title: '开始时间',
      width: 150,
      dataIndex: 'BUSINESS_STARTDATE',
      hideInSearch: true
    },
    {
      title: '办结时间',
      width: 150,
      dataIndex: 'APPLYAPPROVE_DATE',
      hideInSearch: true
    },
    {
      title: '处理时效',
      width: 120,
      dataIndex: 'haveTime',
      hideInSearch: true,
    }
  ]


  useEffect(async () => {
    console.log('compareCurrent', compareCurrent)

    console.log('showReviewProcess', showReviewProcess);
    console.log('compareCurrent', compareCurrent);


    // 拿到流程顺序
    const req: any = {
      SearchParameter: {
        APPROVALROUTE_VALID: 1,
        OPERATION_TYPES: OPERATION_TYPES || 12
      },
      SortStr: 'APPROVALROUTE_STATE asc',
      PageIndex: 1,
      PageSize: 999999
    }
    let allData = await handleGetAPPROVALROUTEList(req)
    if (OPERATION_TYPES === 12 || !OPERATION_TYPES) {
      let list: any = []
      if (allData && allData.length > 0) {
        allData.forEach((item: any) => {
          if (item.APPROVALROUTE_STATE !== 2050 && item.APPROVALROUTE_STATE !== 2060) {
            list.push(item)
          }
        })
      }
      allData = list
    }
    console.log('allData23123123123213123123', allData)
    if (inItiate) {
      const req: any = {
        SearchParameter: {
          TABLE_IDS: compareCurrent?.BILL_ID
        },
        PageIndex: 1,
        PageSize: 999999
      }
      const data = await handleGetAPPLYAPPROVEList(req)
      console.log('allExamine', data);
      if (data && data.length > 0) {
        let obj: any = data[0]
        obj.personName = obj.STAFF_NAME
        obj.personId = obj.STAFF_ID
        setFirstStepDetail(obj)
      }
      let afterList: any = []
      let currentStateIndex: number = 0
      if (allData && allData.length > 0) {
        allData.forEach((item: any, index: number) => {
          if (item.APPROVALROUTE_STATE >= compareCurrent.BILL_STATE) {
            if (item.APPROVALROUTE_STATE === compareCurrent.BILL_STATE) {
              currentStateIndex = index
              item.status = 'process'
              item.APPLYAPPROVE_INFO = '审批中'
              if (data && data.length > 0) {
                let obj: any = data[data.length - 1]
                item.personName = obj.APPLYAPPROVE_NAME.split('-')[0]
                item.personId = obj.APPLYAPPROVE_NAME.split('-')[1]
              }
            }
            afterList.push(item)
          } else if (item.APPROVALROUTE_STATE > 1000 && item.APPROVALROUTE_STATE < compareCurrent.BILL_STATE) {
            if (data && data.length > 0) {
              let obj: any = {}
              data.forEach((subItem: any, subIndex: number) => {
                if (subItem.APPLYAPPROVE_TYPE === item.APPROVALROUTE_STATE) {
                  obj = data[subIndex - 1]
                  subItem.status = 'finish'
                  subItem.APPROVALROUTE_NAME = item.APPROVALROUTE_NAME
                  subItem.personName = subItem.APPLYAPPROVE_NAME.split('-')[0]
                  subItem.personId = subItem.APPLYAPPROVE_NAME.split('-')[1]
                  afterList.push(subItem)
                }
              })
            }
            // item.status = 'finish'
          }
        })
      }
      console.log('afterList', afterList);
      setProgressList(afterList)
    } else {
      if (allData && allData.length > 0) {
        if (showReviewProcess && compareCurrent?.BusinessApprovalId) {
          if (!compareCurrent?.BusinessApprovalId) {
            return
          }
          const req: any = {
            BUSINESSAPPROVALId: compareCurrent?.BusinessApprovalId
          }
          const data = await handleGetGetBUSINESSAPPROVALDetail(req)
          if (data.BUSINESSAPPROVAL_STATE === 1000 && data.BUSINESSAPPROVAL_DESC && changeDesc) {
            changeDesc.current?.setFieldsValue({ BUSINESSAPPROVAL_DESC: data.BUSINESSAPPROVAL_DESC })
          }


          console.log('data2323', data)
          setProgressDetail(data)
          setDefaultTableData(data)
          // 判断有没有被审核过 没有的话 就直接补上后面的 且补上最近流程的状态
          if (data.approveList && data.approveList.length > 0) {
            // 返回的approveList 没有当前这步 所以要补上
            let resList: any = []
            resList = data.approveList
            // resList.push({STAFF_NAME: data.STAFF_NAME,
            //   APPLYAPPROVE_NAME: data.BUSINESSAPPROVAL_NAME,
            //   APPLYAPPROVE_INFO: data.BUSINESSAPPROVAL_DESC,
            //   APPLYAPPROVE_DATE: data.BUSINESS_STARTDATE,
            //   status:'finish'})
            setCurrentSort(data.approveList.length + 2)
            // 状态都是从小到大排序的 当前这步已完成的状态肯定是最大的 所以补齐剩下的状态
            // 未达到的第一个流程 肯定就是当前流程
            let isFirst: boolean = true
            allData.forEach((item: any) => {
              if (item.APPROVALROUTE_STATE >= data.BUSINESSAPPROVAL_STATE) {
                if (isFirst && item.APPROVALROUTE_STATE !== 9000) {
                  item.status = 'process'
                  item.APPLYAPPROVE_INFO = '审核中'
                  isFirst = false
                  item.STAFF_NAME = data.APPOVED_NAME
                } else {
                  item.status = 'wait'
                }
                if (item.APPROVALROUTE_STATE === 9000) {
                  item.APPLYAPPROVE_DATE = data.BUSINESS_ENDDATE
                }
                item.APPLYAPPROVE_NAME = item.APPROVALROUTE_NAME
                resList.push(item)
              }
            })
            console.log('resList', resList);
            setProgressList(resList)
          } else {
            let resList: any = []
            let isFirst: boolean = true
            resList.push({
              STAFF_NAME: data.APPOVED_NAME,
              APPLYAPPROVE_NAME: data.BUSINESSAPPROVAL_NAME,
              APPLYAPPROVE_INFO: '审批中',
              status: 'process'
            })
            allData.forEach((item: any) => {
              if (item.APPROVALROUTE_STATE > data.BUSINESSAPPROVAL_STATE) {
                item.status = 'wait'
                item.APPLYAPPROVE_NAME = item.APPROVALROUTE_NAME
                resList.push(item)
              }
            })
            console.log('resList', resList);
            setProgressList(resList)
          }
        } else {
          // 把是1000的排除掉 因为1000 直接当做发起申请
          let resList: any = []
          allData.forEach((item: any) => {
            if (item.APPROVALROUTE_STATE !== 1000) {
              resList.push({
                APPLYAPPROVE_NAME: item.APPROVALROUTE_NAME,
              })
            }
          })
          setProgressList(resList)
        }
      }
    }


  }, [showReviewProcess])

  // useEffect(async ()=>{
  //   if (showReviewProcess){
  //     const req: any = {
  //       BUSINESSAPPROVALId: compareCurrent?.BusinessApprovalId
  //     }
  //     const data = await handleGetGetBUSINESSAPPROVALDetail(req)
  //     console.log('data',data)
  //     setProgressDetail(data)
  //     setProgressList(data.approveList)
  //   }
  // },[showReviewProcess])

  return (
    <div>
      <Card title="流程进度" bordered style={{ marginBottom: '12px', cursor: 'pointer' }} onClick={() => {
        if (compareCurrent?.BusinessApprovalId) {
          setShowProcessDrawer(true);
        }
      }}>
        {
          inItiate ?
            <div className={"processBox"}>
              <Steps
                size="small"
                current={compareCurrent?.BILL_STATE === 9000 ? progressList && progressList.length ? progressList.length + 1 : '' : currentSort}
                className="site-navigation-steps"
              >
                <Step style={{ height: '50px' }} status={compareCurrent?.BILL_STATE > 1000 ? 'finish' : 'wait'} title="发起申请" description={<div>
                  <Tooltip title={`${firstStepDetail?.personName || ''}${firstStepDetail?.APPLYAPPROVE_INFO ? `：${firstStepDetail?.APPLYAPPROVE_INFO}` : ''}`}>
                    <p>{`${firstStepDetail?.APPLYAPPROVE_DATE || ''}`}</p>
                  </Tooltip>
                </div>} />

                {
                  progressList && progressList.length > 0 ?
                    progressList.map((item: any, index: number) => {
                      return <Step status={item.status} title={item.APPROVALROUTE_NAME} description={item.APPLYAPPROVE_INFO ?
                        item.status === "process" ?
                          <Tooltip title={`${item.personName || ''}${item.APPLYAPPROVE_DATE ? `：${item.APPLYAPPROVE_DATE}` : ''}`}>
                            <p style={{ color: 'red' }}>{item.APPLYAPPROVE_INFO || '-'}</p>
                          </Tooltip>
                          :
                          <div>
                            <Tooltip title={`${item.personName || ''}${item.APPLYAPPROVE_INFO ? `：${item.APPLYAPPROVE_INFO}` : ''}`}>
                              <p>{`${item.APPLYAPPROVE_DATE || ''}`}</p>
                            </Tooltip>
                          </div> : ''} />
                    }) : ''
                }

              </Steps>
            </div> :
            <div className={'processBox'}>
              <Steps
                size="small"
                current={compareCurrent?.BusinessProcess_State === 9000 ? progressList && progressList.length ? progressList.length + 1 : '' : currentSort}
                className="site-navigation-steps"
              >
                <Step style={{ height: '50px' }} status={compareCurrent?.BusinessApprovalId ? 'finish' : 'wait'} title="发起申请" description={<div>
                  <Tooltip title={`${progressDetail?.STAFF_NAME || ''}${progressDetail?.BUSINESSAPPROVAL_DESC ? `：${progressDetail?.BUSINESSAPPROVAL_DESC}` : ''}`}>
                    <p>{`${progressDetail?.BUSINESS_STARTDATE || ''}`}</p>
                  </Tooltip>
                </div>} />
                {
                  progressList && progressList.length > 0 ?
                    progressList.map((item: any, index: number) => {
                      return <Step status={item.status} title={item.APPLYAPPROVE_NAME} description={item.APPLYAPPROVE_INFO ?
                        item.status === "process" ?
                          <Tooltip title={`${item.STAFF_NAME || ''}${item.APPLYAPPROVE_DATE ? `：${item.APPLYAPPROVE_DATE}` : ''}`}>
                            <span style={{ color: 'red' }}>{item.APPLYAPPROVE_INFO}</span>
                          </Tooltip>
                          :
                          <div>
                            <Tooltip title={`${item.STAFF_NAME || ''}${item.APPLYAPPROVE_INFO ? `：${item.APPLYAPPROVE_INFO}` : ''}`}>
                              <p>{`${item.APPLYAPPROVE_DATE || ''}`}</p>
                            </Tooltip>
                          </div> : ''} />
                    }) : ''
                }

                {/* {
              compareCurrent?.BusinessProcess_State === 9000 ?
                <Step status={'process'} title="已审结" description={<div>
                  <Tooltip title={`${compareCurrent?.ApproveStaff_Name || ''}`}>
                    <p>{`${compareCurrent?.BusinessProcess_EndDate || ''}`}</p>
                  </Tooltip>
                </div>} />
                : ''
            } */}
              </Steps>
            </div>
        }


      </Card>

      <Drawer
        width="80%"
        visible={showProcessDrawer} // 抽屉弹框是否显示状态
        onClose={() => { // 关闭抽屉 则在清空选中行数据 并 设置抽屉状态为关闭
          setShowProcessDrawer(false);
        }}
        destroyOnClose
        bodyStyle={{ backgroundColor: "#fff", padding: 16 }}
        closable={false}
      >
        <ProTable
          actionRef={actionRef}
          formRef={formRef}
          columns={columns}
          search={false}
          pagination={false}
          options={false}
          bordered
          style={{ paddingTop: '24px' }}
          request={async () => {
            const req: any = {
              BUSINESSAPPROVALId: compareCurrent?.BusinessApprovalId
            }
            const data = await handleGetGetBUSINESSAPPROVALDetail(req)
            console.log('data32323', data);
            let res: any = data.approveList
            console.log('defaultTableData', defaultTableData);
            // let res: any = defaultTableData.approveList
            // let result: any = []
            // if(res && res.length>0){
            //   res.forEach((item: any)=>{
            //     if(item.)
            //   })
            // }
            // result.unshift({

            // })
            if (res && res.length > 0) {
              // 开始时间就是上一环节的办结时间
              res.forEach((item: any, index: number) => {
                if (index === 0) {
                  item.BUSINESS_STARTDATE = defaultTableData?.BUSINESS_STARTDATE
                } else {
                  item.BUSINESS_STARTDATE = res[index - 1].APPLYAPPROVE_DATE
                }
              })

              res.unshift({
                APPLYAPPROVE_NAME: '发起申请',
                STAFF_NAME: data?.STAFF_NAME || '',
                APPLYAPPROVE_INFO: defaultTableData?.BUSINESSAPPROVAL_DESC || '',
                BUSINESS_STARTDATE: defaultTableData?.BUSINESS_STARTDATE || '',
              })

              if (data.BUSINESSAPPROVAL_STATE !== 9000) {
                res.push({
                  APPLYAPPROVE_NAME: defaultTableData?.BUSINESSAPPROVAL_NAME,
                  STAFF_NAME: defaultTableData?.APPOVED_NAME || '',
                  APPLYAPPROVE_INFO: '',
                  BUSINESS_STARTDATE: res[res.length - 1].APPLYAPPROVE_DATE,
                })
              }



              // 处理时效字段
              res.forEach((item: any) => {
                if (item.BUSINESS_STARTDATE && item.APPLYAPPROVE_DATE) {
                  // 时间戳
                  let timeNumber: any = moment(item.APPLYAPPROVE_DATE).diff(item.BUSINESS_STARTDATE) / 1000

                  // 一小时以内
                  if (timeNumber < 3600) {
                    item.haveTime = (timeNumber / 60).toFixed(2) + '分钟'
                  } else if (timeNumber < 86400) {
                    // 一天以内
                    let hour: any = Math.floor(timeNumber / 3600)

                    let min: any = ((timeNumber - (Math.floor(timeNumber / 3600) * 3600)) / 60).toFixed(0)
                    item.haveTime = `${hour}时${min}分`
                  } else {
                    // 一天以上
                    // 带小数
                    let allTime: any = moment(item.APPLYAPPROVE_DATE).diff(item.BUSINESS_STARTDATE, 'days', true)

                    // 整数
                    let time: any = moment(item.APPLYAPPROVE_DATE).diff(item.BUSINESS_STARTDATE, 'days')
                    let small = getFractionalPart(allTime)
                    let hour: any = Math.floor(small * 24)
                    item.haveTime = `${time}天${hour ? `${hour}时` : ''}`
                  }
                }
              })


              return { data: res, success: true }
            } else if (data.BUSINESSAPPROVAL_STATE === 2000) {
              let list: any = []
              list.push({
                APPLYAPPROVE_NAME: '发起申请',
                STAFF_NAME: defaultTableData?.STAFF_NAME || '',
                APPLYAPPROVE_INFO: defaultTableData?.BUSINESSAPPROVAL_DESC || '',
                BUSINESS_STARTDATE: defaultTableData?.BUSINESS_STARTDATE || '',
              })
              list.push({
                APPLYAPPROVE_NAME: data?.BUSINESSAPPROVAL_NAME,
                STAFF_NAME: data?.APPOVED_NAME || '',
                APPLYAPPROVE_INFO: '',
                BUSINESS_STARTDATE: defaultTableData?.BUSINESS_STARTDATE || '',
              })
              return { data: list, success: true }
            }
            return { data: [], success: true }
          }}
        />
      </Drawer>
    </div>
  )
}
export default connect(({ user }: ConnectState) => ({
  currentUser: user.currentUser
}))(ReviewProcess);


