import React, { useRef, useState } from "react";
import type { CurrentUser } from "@/models/user";
import { connect } from "umi";
import type { ConnectState } from "@/models/connect";
import type { ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import type { FormInstance } from "antd";
import { handleGetBUSINESSAPPROVALS } from "@/pages/examine/myApproval/service";
import moment from "moment";
import useRequest from "@ahooksjs/use-request";
import { getFieldEnumTree } from "@/services/options";
import { message, Modal, Popconfirm, Space } from "antd";
import ProForm, { ProFormSelect, ProFormTextArea } from "@ant-design/pro-form";
import { handleApproveAccount, handleRejectAccount } from "@/pages/examine/reconciliationApproval/base/service";
import { handleGetGetBUSINESSAPPROVALDetail } from "@/pages/reports/ShopExpenseDetail/service";
import session from "@/utils/session";
import { handleGetBUSINESSAPPROVALDetail } from "../monthSettlement/service";
import { handleGetAPPROVALROUTEList } from "@/pages/Setting/serviceConfig/service";
import { handleGetMonthAccountProinst } from "../examineList/service";

const myApproval: React.FC<{ currentUser?: CurrentUser }> = (props) => {
  const { currentUser } = props
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const formDescRef = useRef<any>();

  // 业务类型的obj格式
  const [serviceTypeObj, setServiceTypeObj] = useState<any>()
  // 加载业务类型
  const { loading: treeLoading, data: treeViews } = useRequest(async () => {
    const data = await getFieldEnumTree({ FieldExplainField: 'PROCESS_TYPE', sessionName: 'PROCESS_TYPE' })
    const list: any = []
    if (data && data.length > 0) {
      data.forEach((item: any) => {
        const childrenList: any = []
        if (item.children && item.children.length > 0) {
          item.children.forEach((subItem: any) => {
            childrenList.push({ label: subItem.label, value: subItem.value })
          })
        }
        list.push({ label: item.label, value: item.value, disabled: true, children: childrenList })
      })
    }
    setServiceTypeObj(list)

    return list
  })

  const [getType, setGetType] = useState<number>(0)
  const [proinstRow, setProinstRow] = useState<any>()
  const [showDescModal, setShowDescModal] = useState<boolean>(false)
  const [descText, setDescText] = useState<string>()

  const PROCESS_TYPETree = session.get('PROCESS_TYPETree')
  const PROCESS_TYPEObj = session.get('PROCESS_TYPEObj')

  const columns: any = [
    {
      title: '业务名称',
      width: 250,
      ellipsis: true,
      dataIndex: 'BusinessProcess_Name',
      hideInSearch: true
    },
    // {
    //   title:'业务类型',
    //   width: 140,
    //   hideInTable: true,
    //   dataIndex:'OPERATION_TYPE',
    //   valueType: 'treeSelect',
    //   fieldProps:{
    //     treeDefaultExpandAll: true,
    //   },
    //   // valueEnum: treeViews
    //   request:async ()=>{
    //     const data = await getFieldEnumTree({ FieldExplainField: 'PROCESS_TYPE', sessionName: 'PROCESS_TYPE' })
    //     if (data && data.length>0){
    //       data.forEach((item: any)=>{
    //         item.disabled = true
    //       })
    //     }
    //     return data
    //   }
    // },
    {
      title: '业务类型',
      width: 140,
      hideInSearch: true,
      dataIndex: 'Operation_Type',
      valueType: 'select',
      valueEnum: PROCESS_TYPEObj
    },
    {
      title: '服务区名称',
      width: 200,
      ellipsis: true,
      dataIndex: 'Serverpart_Name',
      hideInSearch: true
    },
    {
      title: '经办人',
      width: 150,
      dataIndex: 'Staff_Name',
      hideInSearch: true,
      ellipsis: true,
    },
    // {
    //   title:'驳回人员',
    //   width: 100,
    //   dataIndex:'REJECTSTAFF_NAME',
    //   hideInSearch: true
    // },
    // {
    //   title:'驳回意见',
    //   width: 200,
    //   ellipsis:true,
    //   dataIndex:'REJECT_INFO',
    //   hideInSearch: true
    // },
    {
      title: '业务状态',
      dataIndex: 'BusinessProcess_State',
      hideInSearch: true,
      valueType: 'select',
      width: 150,
      request: async () => {
        const req: any = {
          SearchParameter: {
            APPROVALROUTE_VALID: 1,
            OPERATION_TYPES: 11
          },
          SortStr: 'APPROVALROUTE_STATE asc',
          PageIndex: 1,
          PageSize: 999999
        }
        const data = await handleGetAPPROVALROUTEList(req)
        if (data && data.length > 0) {
          const list: any = []
          data.forEach((item: any) => {
            list.push({ label: item.APPROVALROUTE_NAME, value: item.APPROVALROUTE_STATE })
          })
          list.push({ label: '已审结', value: 9000 })
          list.push({ label: '已驳回', value: 3000 })
          let str: string = ''
          list.forEach((item: any) => {
            if (item.value === 3000) {

            } else {
              if (str) {
                str += `,${item.value}`
              } else {
                str = item.value
              }
            }
          })
          return list
        }
        return []
      }
    },
    {
      title: '备注说明',
      width: 200,
      ellipsis: true,
      dataIndex: 'BusinessProcess_Desc',
      hideInSearch: true
    },
    {
      title: '累计营业额',
      width: 120,
      ellipsis: true,
      dataIndex: 'REVENUE_AMOUNT',
      hideInSearch: true,
      valueType: 'digit'
    },
    {
      title: '待审核人名称',
      width: 180,
      ellipsis: true,
      dataIndex: 'ApproveStaff_Name',
      hideInSearch: true
    },
    {
      title: '业务时间',
      width: 180,
      ellipsis: true,
      dataIndex: 'BusinessProcess_StartDate',
      hideInSearch: true
    },
    {
      dataIndex: 'option',
      title: '操作',
      width: 120,
      valueType: 'option',
      align: 'center',
      fixed: 'right',
      hideInSearch: true,
      render: (_, record) => {
        return (
          <Space>
            <Popconfirm
              title="确认通过审核？"
              onConfirm={async () => {
                setGetType(1)
                setProinstRow(record)
                setShowDescModal(true)
              }}
            >
              <a>审核</a>
            </Popconfirm>
            <Popconfirm
              title="确认驳回？"
              onConfirm={async () => {
                setGetType(2)
                setProinstRow(record)
                setShowDescModal(true)
              }}
            >
              <a>驳回</a>
            </Popconfirm>
          </Space>
        )
      }
    }
  ]

  // 驳回还是审核 审核1 驳回2
  const handleGetToExamine = async (desc: string, target: any, nextPerson: any) => {
    let req: any = {}
    let data: any = {}
    // 审核
    if (getType === 1) {
      req = {
        businessApprovalID: proinstRow?.BusinessApproval_ID,
        curProinstState: proinstRow.BusinessProcess_State,
        approveedInfo: desc,
        approveedStaffId: currentUser?.ID,
        approveedStaffName: currentUser?.Name,
        nextId: nextPerson
        // targetProinstState: target
      }
      data = await handleApproveAccount(req)
    } else if (getType === 2) {
      //   驳回
      const backObj = JSON.parse(target)
      req = {
        businessApprovalID: proinstRow?.BusinessApproval_ID,
        approveedStaffId: currentUser?.ID,
        approveedStaffName: currentUser?.Name,
        approveedInfo: desc,
        targetProinstState: backObj?.APPROVALROUTE_STATE
      }
      data = await handleRejectAccount(req)
    }

    if (data.Result_Code === 100) {
      message.success(data.Result_Desc)
    } else {
      message.error(data.Result_Desc)
    }
    setShowDescModal(false)
    actionRef.current?.reload()
    setGetType(0)
    formDescRef.current.setFieldsValue({ desc: '' })
  }

  return <div style={{ width: '100%', backgroundColor: '#fff' }}>
    <ProTable
      actionRef={actionRef}
      formRef={formRef}
      columns={columns}
      bordered
      request={async (params) => {
        const req: any = {
          SearchParameter: {
            // BusinessProcess_Name: params.BusinessProcess_Name,
            BusinessProcess_StateSearch: params.BusinessProcess_State || '',
            Operation_Type: 11
          },
          keyWord: params.BusinessProcess_Name ? {
            key: "BusinessProcess_Name",
            value: params.BusinessProcess_Name
          } : '',
          SortStr: "BusinessProcess_StartDate desc",
          pageindex: 1,
          pagesize: 999999
        }
        const data = await handleGetMonthAccountProinst(req)
        if (data && data.length > 0) {
          return { data, success: true }
        }
        return { data: [], success: true }
      }}
      pagination={false}
      scroll={{ x: 1100, y: 'calc(100vh - 500px)' }}
    />


    {/* 审核驳回时输入的 */}
    <Modal
      title={getType === 1 ? '审核' : '驳回'}
      open={showDescModal}
      width={700}
      destroyOnClose
      onOk={() => {
        formDescRef.current.validateFields().then(res => {
          if (res.desc) {
            // setDescText(res.desc)
            handleGetToExamine(res.desc, res.targetProinstState, res.APPROVALSTAFF_ID)
            setDescText('')
          }
        })

      }}
      onCancel={() => {
        formDescRef.current?.resetFields()
        setShowDescModal(false)
        setDescText('')
      }}>
      <ProForm
        formRef={formDescRef}
        submitter={{
          // 清空表单自带的按钮
          render: (props, doms) => {
            return []
          }
        }}
      >
        {/* 要驳回的状态 */}
        {
          getType === 2 ?
            <ProFormSelect
              name="targetProinstState"
              label="回退状态"
              rules={[
                {
                  required: true,
                  message: '请输入备注说明'
                }
              ]}
              request={async () => {
                const req: any = {
                  BUSINESSAPPROVALId: proinstRow?.BusinessApproval_ID
                }
                const data = await handleGetGetBUSINESSAPPROVALDetail(req)
                if (data.rejectList && data.rejectList.length > 0) {
                  const list: any = []

                  data.rejectList.forEach((item: any) => {
                    list.push({ label: item.APPROVALROUTE_NAME, value: JSON.stringify(item) })
                  })
                  return list
                }
              }}
            />
            : ''
        }

        {
          getType === 1 && proinstRow?.NextState !== 9000 ?
            <ProFormSelect
              name="APPROVALSTAFF_ID"
              label="审批人"
              rules={[
                {
                  required: true,
                  message: '请选择审批人'
                }
              ]}
              request={async () => {
                const req: any = {
                  BUSINESSAPPROVALId: proinstRow?.BusinessApproval_ID
                }
                const data = await handleGetGetBUSINESSAPPROVALDetail(req)
                const list: any = []
                if (data.UserList && data.UserList.length > 0) {
                  data.UserList.forEach((item: any) => {
                    if (item.USER_STATUS === 1) {
                      list.push({ label: item.USER_NAME, value: item.USER_ID })
                    }
                  })
                }
                if (list && list.length > 0 && list.length === 1) {
                  formDescRef.current?.setFieldsValue({ nextPerson: list[0].value })
                }
                return list
              }}
            /> : ''
        }
        <ProFormTextArea
          name="desc"
          label="备注说明"
          rules={[
            {
              required: true,
              message: '请输入备注说明'
            }
          ]}
        />
      </ProForm>
      {/* <TextArea row={4} placeholder={'请输入备注说明'} onChange={(e: any)=>{ */}
      {/*   setDescText(e.target.value) */}
      {/* }}/> */}

    </Modal>
  </div>
}

export default connect(({ user }: ConnectState) => ({
  currentUser: user.currentUser
}))(myApproval);
