import { connect } from "umi";
import type { CurrentUser } from "umi";
import type { ConnectState } from "@/models/connect";
import React, { useRef, useState } from "react";
import ProCard from "@ant-design/pro-card";
import { MenuFoldOutlined } from "@ant-design/icons";
import type { FormInstance } from "antd";
import { Popconfirm } from "antd";
import { Avatar, Button, Drawer, Menu, message, Space, Spin, Tree } from "antd";
import useRequest from "@ahooksjs/use-request";
import { getServerpartTree, handleCallLogs } from "@/services/options";
import type { ActionType } from "@ant-design/pro-table";
import ProTable from "@ant-design/pro-table";
import ReactHTMLTableToExcel from "react-html-table-to-excel";
import SubMenu from "antd/lib/menu/SubMenu";
import moment from "moment";
import {
  handleDeleteCHECKACCOUNT,
  handleGetCHECKACCOUNTList,
  handleUpLoadAuditExplain
} from "@/pages/reports/audit/feedback/service";
import AuditDetail from "@/pages/DataVerification/list/components/auditDetail";
import PageTitleBox from "@/components/PageTitleBox";
import LeftSelectTree from "../../settlementAccount/component/leftSelectTree";
import { exportXlsxFromProColumnsExcelJS } from "@/utils/exportExcelFun";
import { formatTreeData } from "@/utils/format";


const checkAcount: React.FC<{ currentUser: CurrentUser }> = (props) => {
  const { currentUser } = props
  const downloadBtnRef = useRef<any>()
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [reqDetailList, setReqDetailList] = useState<any>(); // 合计项数据源
  const [printOut, setPrintOut] = useState<any>(); // 打印数据的内容
  const [collapsible, setCollapsible] = useState<boolean>(false)
  const [treeView, setTreeView] = useState<any>()
  // 加载服务区树
  const { loading: treeLoading, data: treeViews } = useRequest(async () => {
    const data = await getServerpartTree(currentUser?.ProvinceCode, currentUser?.CityAuthority, true, true, true)
    setTreeView(data)
    return data
  })
  // 树相关的属性和方法
  const [selectedId, setSelectedId] = useState<string>()
  // 导出的加载效果
  const [showLoading, setShowLoading] = useState<boolean>(false)
  // 是否显示打印的表格
  const [showExportTable, setShowExportTable] = useState<boolean>(false)
  const [currenMenu, setCurrenMenu] = useState<any>(); // 当前选中左侧菜单的服务区节点
  const [bigCurrenMenu, setBigCurrenMenu] = useState<any>() // 选中片区的节点
  // 点击稽查反馈出现的弹框
  const [inspectionModal, setInspectionModal] = useState<boolean>(false)
  const auditDetailRef = useRef<any>()
  const [currentRow, setCurrentRow] = useState<any>()

  const columns: any = [
    {
      title: '处理状态',
      dataIndex: 'TREATMENT_MARKSTATE',
      hideInTable: true,
      valueType: 'select',
      valueEnum: {
        0: "全部",
        1: "未反馈",
        2: "未冲正",
      },
      initialValue: "0"
    },
    {
      title: '统计时间',
      dataIndex: 'search_date',
      valueType: 'dateRange',
      hideInTable: true,
      hideInDescriptions: true,
      colSize: 1,
      initialValue: [moment().add(-1, 'month').format('YYYY-MM-DD'), moment().add(-1, "day").format('YYYY-MM-DD')],
      search: {
        transform: (value) => {
          return {
            Start_Date: value[0],
            End_Date: value[1],
          };
        },
      },
      fieldProps: {
        disabledDate: (current: any) => current && current > moment()
      }
    },
    {
      title: '图片上传',
      hideInTable: true,
      hideInSearch: true,
      dataIndex: ''
    },
    {
      title: '稽查类型',
      hideInTable: true,
      dataIndex: 'CHECK_TYPE',
      valueType: 'select',
      valueEnum: {
        "": "全部",
        "现场稽查": "现场稽查",
        "区域稽查": "区域稽查",
        "公司稽查": "公司稽查",
      },
      initialValue: ""
    },
    {
      title: '稽核误差率',
      hideInTable: true,
      dataIndex: 'ERROR_RATE',
      valueType: 'select',
      valueEnum: {
        0: '全部',
        1: '大于0.2%'
      },
      initialValue: '1'
    },
    {
      title: '稽核状态',
      hideInTable: true,
      dataIndex: 'VALID',
      valueType: 'select',
      valueEnum: {
        null: '全部',
        1: '有效',
        0: '无效'
      },
      initialValue: '1'
    },
    {
      title: <div style={{ textAlign: 'center' }}>{'序号'}</div>,
      dataIndex: '',
      hideInSearch: true,
      width: 70,
      valueType: 'index'
    },
    {
      title: <div style={{ textAlign: 'center' }}>{'服务区名称'}</div>,
      width: 120,
      dataIndex: 'SERVERPART_NAME',
      hideInSearch: true,
    },
    {
      title: <div style={{ textAlign: 'center' }}>{'门店名称'}</div>,
      width: 150,
      dataIndex: 'SHOPNAME',
      hideInSearch: true,
    },
    {
      title: <div style={{ textAlign: 'center' }}>{'稽核反馈'}</div>,
      width: 200,
      ellipsis: true,
      dataIndex: 'CHECKACCOUNT_DESC',
      hideInSearch: true,
      render: (_, record) => {
        return <a onClick={() => {
          console.log('record', record)
          setCurrentRow({
            ...record,
            Audit_Id: record.CHECKACCOUNT_ID,
            MachineCode: record.MACHINECODE
          })
          setInspectionModal(true)
        }}>
          {record?.CHECKACCOUNT_DESC || '-'}
        </a>
      }
    },
    {
      title: <div style={{ textAlign: 'center' }}>{'稽核误差率'}</div>,
      width: 110,
      hideInSearch: true,
      align: 'right',
      dataIndex: 'ERROR_RATE',
      render: (_, record) => {
        return record?.ERROR_RATE ?
          <span style={{ color: 'red', fontWeight: 'bold' }}>{`${record?.ERROR_RATE}%`}</span>
          : '-'
      }
    },
    {
      title: <div style={{ textAlign: 'center' }}>{'长短款/冲正流水'}</div>,
      width: 130,
      hideInSearch: true,
      align: 'right',
      dataIndex: 'DIFFERENT_PRICE',
      render: (_, record) => {
        return <span style={{ color: record.DIFFERENT_PRICE < 0 || record?.REPLENISH_AMOUNT < 0 ? 'red' : record.DIFFERENT_PRICE > 0 || record?.REPLENISH_AMOUNT > 0 ? '#008000' : '', fontWeight: 'bold' }}>
          {`${record.DIFFERENT_PRICE || '0'}/${record?.REPLENISH_AMOUNT || '0'}`}
        </span>
      }
    },
    {
      title: <div style={{ textAlign: 'center' }}>{'稽核现金/对客现金'}</div>,
      width: 140,
      hideInSearch: true,
      dataIndex: 'CASH',
      align: 'right',
      render: (_, record) => {
        return `${record.CASHPAY || ''}/${record?.CASH || ''}`
      }
    },
    {
      title: <div style={{ textAlign: 'center' }}>{'对客营收'}</div>,
      width: 100,
      hideInSearch: true,
      align: 'right',
      dataIndex: 'TOTALSELLAMOUNT'
    },
    {
      title: <div style={{ textAlign: 'center' }}>{'稽查时间'}</div>,
      width: 160,
      hideInSearch: true,
      align: 'left',
      dataIndex: 'CHECK_ENDDATE',
      render: (_, record) => {
        return record?.CALIBRATOR_DATE ? moment(record?.CHECK_ENDDATE).format('YYYY-MM-DD HH:mm:ss') : '-'
      }
    },
    {
      title: '稽查类型',
      width: 100,
      dataIndex: 'CHECK_TYPE',
      valueType: 'select',
      valueEnum: {
        "": "全部",
        "现场稽查": "现场稽查",
        "区域稽查": "区域稽查",
        "公司稽查": "公司稽查",
      },
      hideInSearch: true
    },
  ]

  const exportTable = (e) => {
    e.stopPropagation();                                            // 防止Collapse组件收起
    const main = document.getElementsByClassName('saleReportHideBox')[0]
    const thead = main.querySelector('thead').cloneNode(true);  // 深克隆DOM节点
    const tbody = main.querySelector('tbody').cloneNode(true);  // 深克隆DOM节点
    const container = document.querySelector('#hiddenBox');

    const tempTable = document.createElement('table');
    tempTable.appendChild(thead);
    tempTable.appendChild(tbody);

    tempTable.setAttribute('id', 'table-to-xls-checkAcount');                    // 给table添加id，值与按钮上的table字段对应

    container.appendChild(tempTable);                                // 把创建的节点添加到页面容器中

    setShowLoading(false)

    downloadBtnRef.current.handleDownload();
    setShowExportTable(false)
    tempTable.remove() // 防止重复打印一个内容
  }
  // 查询的条件
  const [searchParams, setSearchParams] = useState<any>()

  return (
    <div ref={(el) => {
      // 打印报表
      if (!reqDetailList || reqDetailList.length === 0) return;
      setPrintOut(el);
    }} >

      {
        showLoading ?
          <div
            style={{
              width: '100%',
              height: '100%',
              background: 'rgba(0,0,0,0.1)',
              position: 'fixed',
              zIndex: 5,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center'
            }}
          >
            <div style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              padding: '15px 20px 10px',
              background: '#fff',
              borderRadius: '8px',
              width: '200px'
            }}>
              <Spin />
              <span style={{ marginLeft: '5px' }}>数据导出中...</span>
            </div>
          </div> : ''
      }

      <div className={'saleReportHideBox'} style={{ position: 'fixed', zIndex: -1, top: 0, left: 0 }}>
        {
          showExportTable && reqDetailList && reqDetailList.length > 0 ?
            <ProTable
              columns={columns}
              dataSource={reqDetailList}
              pagination={false}
              expandable={{
                defaultExpandAllRows: true
              }}
            /> : ''
        }
      </div>
      <div id='hiddenBox' style={{ position: 'fixed', zIndex: -1, top: 0, left: 0 }} />

      <div style={{ backgroundColor: '#fff', display: 'flex' }}>
        {/* <ProCard
          style={{width:!collapsible ? "300px" : "60px"}}
          className="pageTable-leftnav"
          bodyStyle={{padding: 0, paddingTop: 20, paddingLeft: 20,width:!collapsible ? "300px" : "60px"}}
          extra={<MenuFoldOutlined onClick={() => {
            setCollapsible(!collapsible)
          }}/>}
          colSpan={!collapsible ? "300px" : "60px"}
          title={!collapsible ? "请选择服务区" : ""}
          headerBordered
          collapsed={collapsible}
        >
          {treeView && treeView.length > 0 ? <Tree
            checkable
            treeData={[{
              label: '全部',
              value: 0,
              key: '0-0',
              children: treeView
            }]}
            fieldNames={{
              title: "label",
              key: "key"
            }}
            blockNode
            defaultExpandedKeys={['0-0']}
            onCheck={(checkedKeys: React.Key[] | any, info) => {
              const selectedIds = info.checkedNodes.filter(n => n?.type === 1)
              setSelectedId(selectedIds.map(n => n?.value)?.toString() || '')
              // actionRef?.current?.reload()
              // getData(selectedIds.map(n => n?.value)?.toString() || '')
            }}
            // switcherIcon={<PlusOutlined />}
          /> : ''}
        </ProCard> */}
        <LeftSelectTree setSelectedId={setSelectedId} setCollapsible={setCollapsible} collapsible={collapsible} />

        <div style={{
          width: !collapsible ? 'calc(100% - 300px)' : 'calc(100% - 60px)',
          paddingTop: 0,
          paddingBottom: 0,
          paddingRight: 0
        }}>
          <ProTable
            actionRef={actionRef}
            formRef={formRef}
            columns={columns}
            bordered
            headerTitle={<PageTitleBox props={props} />}
            search={{ span: 6 }}
            request={async (params) => {
              console.log('bigCurrenMenu', bigCurrenMenu)
              console.log('currenMenu', currenMenu)
              if (!selectedId) {
                return
              }
              const req = {
                SearchParameter: {
                  ...params,
                  TREATMENT_MARKSTATE: params.TREATMENT_MARKSTATE === '0' ? '' : params.TREATMENT_MARKSTATE,
                  SERVERPART_IDS: selectedId,
                },
                PageIndex: 1,
                PageSize: 99999
              }
              handleCallLogs()
              setSearchParams(params)
              const data = await handleGetCHECKACCOUNTList(req)
              console.log('data', data)
              if (data && data.length > 0) {

                let fieldData: any = [
                  "TOTALSELLAMOUNT"
                ]
                let enumList: any = []

                let newPrintData: any = formatTreeData(JSON.parse(JSON.stringify(data)), fieldData, enumList, [], [])
                setReqDetailList(newPrintData)
                return { data, success: true }
              }
              return { data: [], success: true }
            }}
            toolbar={{
              actions: [
                // <span style={{ visibility: 'hidden' }}>
                //   <ReactHTMLTableToExcel
                //     buttonText={'导出excel'}
                //     ref={downloadBtnRef}
                //     table="table-to-xls-checkAcount"
                //     filename={`现场稽核管理${searchParams?.Start_Date}-${searchParams?.End_Date}`}
                //     sheet="sheet1"
                //   />
                // </span>,
                <Button
                  key="new"
                  type="primary"
                  onClick={(e) => {
                    if (reqDetailList && reqDetailList.length > 0) {
                      // 尝试一下 导出新方法 
                      exportXlsxFromProColumnsExcelJS(columns,
                        reqDetailList,
                        `现场稽核管理${searchParams?.Start_Date}-${searchParams?.End_Date}`,
                        {
                          footerMaker: currentUser?.Name,
                          footerMakerTime: moment().format('YYYY-MM-DD HH:mm:ss'),
                          footerStatsTime: `${searchParams?.Start_Date}-${searchParams?.End_Date}`
                        }
                      )
                    } else {
                      message.error('暂无数据可导出！')
                    }
                  }}
                >
                  导出excel
                </Button>
              ]
            }}
          />
        </div>
      </div>

      <Drawer
        width={'50%'}
        visible={inspectionModal}
        closable={false}
        bodyStyle={{ padding: 0 }}
        onClose={() => {
          setCurrentRow(undefined)
          setInspectionModal(false);
        }}
        destroyOnClose={true}
        footer={<div style={{ display: 'flex', width: '100%', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <Button danger onClick={() => {
              auditDetailRef.current.setShowMoadl(!auditDetailRef.current.showModal)
            }}>上传单据</Button>
          </div>
          <div>
            <Button style={{ marginRight: '8px' }} onClick={() => {
              setCurrentRow(undefined)
              setInspectionModal(false);
            }}>取消</Button>
            <Popconfirm  // 删除按钮功能
              title="确定设置为无效?"
              onConfirm={async () => {
                const req: any = {
                  CHECKACCOUNTId: currentRow?.Audit_Id
                }
                console.log('req', req)
                const data = await handleDeleteCHECKACCOUNT(req)
                if (data.Result_Code === 100) {
                  message.success(data.Result_Desc)
                  setCurrentRow(undefined)
                  setInspectionModal(false);
                  actionRef.current?.reload()
                } else {
                  message.error(data.Result_Desc)
                }
              }}
            >
              <Button danger style={{ marginRight: '8px' }}>设为无效</Button>
            </Popconfirm>
            <Button type='primary' onClick={async () => {
              auditDetailRef.current?.auditFormRef.current.validateFields().then(async (res: any) => {
                if (res) {
                  const res: any = auditDetailRef.current?.auditFormRef.current.getFieldsValue()
                  const detailObj: any = auditDetailRef.current?.detailRow
                  const imgList: any = auditDetailRef.current?.picList
                  let imgStr: string = ''
                  if (imgList && imgList.length > 0) {
                    imgList.forEach((item: any) => {
                      if (imgStr) {
                        imgStr += `,${item.url}`
                      } else {
                        imgStr = item.url
                      }
                    })
                  }
                  const req: any = {
                    CheckAccount_Id: currentRow.Audit_Id,
                    auditExplain: res?.CheckAccount_Desc,
                    isAddIn: !detailObj?.Add_Amount && detailObj?.Add_Amount !== 0, // 有值false 没值true
                    imageInfo: imgStr,
                    // memberShipId:'',
                    provinceCode: currentUser.ProvinceCode,
                    addAmout: res?.Add_Amount
                  }
                  const data = await handleUpLoadAuditExplain(req)
                  if (data.Result_Code === 100) {
                    message.success(data.Result_Desc)
                    setCurrentRow(undefined)
                    setInspectionModal(false);
                    actionRef.current?.reload()
                  } else {
                    message.error(data.Result_Desc)
                  }
                }
              })
            }}>保存</Button>
          </div>
        </div>}
      >
        <AuditDetail onRef={auditDetailRef} isShow={inspectionModal} rowDetail={currentRow} currentDetail={currentRow} />
      </Drawer>
    </div>
  )
}

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