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 { Col, Drawer, Row, Select } from "antd";
import { Modal } from "antd";
import { Avatar, Button, Menu, message, Space, Spin, Tree } from "antd";
import useRequest from "@ahooksjs/use-request";
import { getServerpartTree, getSPRegionShopTree, handleCallLogs } from "@/services/options";
import type { ActionType } from "@ant-design/pro-table";
import ProTable from "@ant-design/pro-table";
import moment from "moment";
import {
  handleGetAuditTasksReport,
  handleSynchroAUDITTASKS
} from "@/pages/reports/audit/auditTasks/service";
import { handleGetAuditTasksDetail } from './service'
import ProForm, { ProFormDatePicker, ProFormTextArea } from "@ant-design/pro-form";
import './style.less'
import PageTitleBox from "@/components/PageTitleBox";
import LeftSelectTree from "../../settlementAccount/component/leftSelectTree";

const auditTasks: React.FC<{ currentUser: CurrentUser }> = (props) => {
  const { currentUser } = props
  const modalFormRef = useRef<any>();
  const downloadBtnRef = useRef<any>()
  const actionRef = useRef<ActionType>();
  const actionDrawerRef = 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 [shopTreeView, setShopTreeView] = 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 { loading: shopTreeLoading, data: shopTree } = useRequest(async () => {
    const data = await getSPRegionShopTree(currentUser?.ProvinceCode, '', '', '', '1000,2000', '2000,3000,4000', true, true, true, 'SERVERPARTSHOP_INDEX,BUSINESS_STATE,SHOPSHORTNAME', false, true);
    setShopTreeView(data)
    return data
  })
  // 树相关的属性和方法
  const [selectedId, setSelectedId] = useState<string>()
  const [selectedModalId, setSelectedModalId] = useState<string>()
  // 导出的加载效果
  const [showLoading, setShowLoading] = useState<boolean>(false)
  // 是否显示打印的表格
  const [showExportTable, setShowExportTable] = useState<boolean>(false)
  const [currenMenu, setCurrenMenu] = useState<any>(); // 当前选中左侧菜单的服务区节点
  // 展示添加弹出框
  const [showModal, setShowModal] = useState<boolean>(false)
  // 弹出框的表格数据
  const [modalProTableData, setModalProTableData] = useState<any>([{ time: 18, index: 1 }])
  // 时间选择器的时间
  const timeSelect: any = [
    { label: "8:00", value: 8 },
    { label: "9:00", value: 9 },
    { label: "10:00", value: 10 },
    { label: "11:00", value: 11 },
    { label: "12:00", value: 12 },
    { label: "13:00", value: 13 },
    { label: "14:00", value: 14 },
    { label: "15:00", value: 15 },
    { label: "16:00", value: 16 },
    { label: "17:00", value: 17 },
    { label: "18:00", value: 18 },
    { label: "19:00", value: 19 },
    { label: "20:00", value: 20 },
  ]
  // 详情抽屉
  const [showDetailDrawer, setShowDetailDrawer] = useState<boolean>(false)
  // 行详情
  const [currentRow, setCurrentRow] = useState<any>()


  const columns: any = [
    {
      title: '统计时间',
      dataIndex: 'search_date',
      valueType: 'dateRange',
      hideInTable: true,
      hideInDescriptions: true,
      colSize: 1,
      initialValue: [moment().add(-1, 'month').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')],
      search: {
        transform: (value) => {
          return {
            startDate: value[0],
            endDate: value[1],
          };
        },
      },
      fieldProps: {
        disabledDate: (current: any) => current && current > moment()
      }
    },
    // {
    //   title:'有效状态',
    //   dataIndex: 'VALID',
    //   hideInTable: true,
    //   hideInDescriptions: true,
    //   valueType: 'select',
    //   valueEnum:{
    //     '':{ text: '全部' },
    //     0: { text: '无效' },
    //     1: { text: '有效' },
    //   },
    //   initialValue: "1"
    // },
    {
      title: '序号',
      hideInSearch: true,
      width: 70,
      valueType: 'index',
      align: 'center',
      dataIndex: 'index'
    },
    {
      title: '业态数量',
      width: 120,
      hideInSearch: true,
      align: 'center',
      dataIndex: 'BusinessTypeCount',
      render: (_, record) => {
        return record?.BusinessTypeCount ? <a onClick={() => {
          console.log('record', record)
          setCurrentRow(record)
          setShowDetailDrawer(true)
          actionDrawerRef.current?.reload()
        }}>{record?.BusinessTypeCount}</a> : '-'
      }
    },
    {
      title: '稽核日期',
      width: 150,
      align: 'center',
      hideInSearch: true,
      dataIndex: 'AuditTasksStartDate',
      render: (_, record) => {
        return record?.AuditTasksStartDate ? moment(record?.AuditTasksStartDate).format('YYYY-MM-DD') : '-'
      }
    },
    {
      title: '稽核时间',
      width: 150,
      align: 'center',
      hideInSearch: true,
      dataIndex: 'StratTime'
    },
    {
      title: '下发人员',
      width: 150,
      align: 'center',
      hideInSearch: true,
      dataIndex: 'StaffName'
    },
    {
      title: '下发时间',
      width: 150,
      align: 'center',
      hideInSearch: true,
      dataIndex: 'OperateDate',
      render: (_, record) => {
        return record?.OperateDate ? moment(record?.OperateDate).format('YYYY-MM-DD HH:mm:ss') : '-'
      }
    },
    {
      title: '备注说明',
      width: 250,
      ellipsis: true,
      align: 'center',
      hideInSearch: true,
      dataIndex: 'AuditTasksDesc'
    },
  ]

  const modalColumns: any = [
    {
      title: '序号',
      dataIndex: 'index',
      // valueType:'index',
      width: 70,
    },
    {
      title: '操作',
      dataIndex: '',
      width: 100,
      render: (_, record) => {
        return <Button type={'primary'} onClick={() => {
          const newList: any = []
          const list: any = JSON.parse(JSON.stringify(modalProTableData))
          list.forEach((item: any) => {
            if (item.index !== record.index) {
              newList.push(item)
            }
          })
          if (newList && newList.length > 0) {
            newList.forEach((item: any, index: number) => {
              item.index = index + 1
            })
          }
          setModalProTableData(newList)
        }}>删除</Button>
      }
    },
    {
      title: '稽核时间',
      dataIndex: 'time',
      width: 150,
      render: (_, record) => {
        return <Select
          style={{ width: '120px' }}
          options={timeSelect}
          value={record.time}
          onChange={(e: any) => {
            const list: any = JSON.parse(JSON.stringify(modalProTableData))
            list.forEach((item: any, index: number) => {
              if (item.index === record?.index) {
                item.time = e
              }
            })
            setModalProTableData(list)
          }}
        >

        </Select>
      }
    }
  ]

  const drawerColumns: any = [
    {
      title: '序号',
      valueType: 'index',
      dataIndex: ''
    },
    {
      title: '指令时间',
      dataIndex: 'StratTime'
    },
    {
      title: '稽查时间',
      dataIndex: 'CheckEndDate',
      render: (_, record) => {
        return record?.CheckEndDate ? moment(record?.CheckEndDate).format('YYYY-MM-DD') : '-'
      }
    },
    {
      title: '现金营收',
      dataIndex: 'Cash'
    },
    {
      title: '长短款',
      dataIndex: 'DifferentPrice'
    },
    {
      title: '稽核误差率(%)',
      dataIndex: 'ErrorRate'
    },
    {
      title: '开始时间',
      dataIndex: 'AuditTasksStartDate',
      render: (_, record) => {
        return record?.AuditTasksStartDate ? moment(record?.AuditTasksStartDate).format('YYYY-MM-DD') : '-'
      }
    },
    {
      title: '服务区名称',
      dataIndex: 'ServerpartName'
    },
    {
      title: '门店名称',
      dataIndex: 'ShopName'
    },
    {
      title: '操作说明',
      dataIndex: 'AuditTasksDesc'
    },
  ]

  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-auditTasks');                    // 给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) => {
              if (!selectedId) {
                return
              }
              const req = {
                ...params,
                ServerpartIds: selectedId,
              }
              handleCallLogs()
              setSearchParams(params)
              const data = await handleGetAuditTasksReport(req)
              console.log('data', data)
              if (data && data.length > 0) {
                setReqDetailList(data)
                return { data, success: true }
              }
              return { data: [], success: true }
            }}
            toolbar={{
              actions: [
                <Button
                  key="new"
                  type="primary"
                  onClick={(e) => {
                    setShowModal(true)
                  }}
                >
                  添加
                </Button>
              ]
            }}
          />
        </div>
      </div>

      <Modal
        open={showModal}
        width={1400}
        wrapClassName={'shopModal'}
        destroyOnClose
        onCancel={() => {
          setShowModal(false)
          setSelectedModalId(undefined)
          setModalProTableData([])
        }}
        onOk={async () => {
          modalFormRef.current.validateFields().then(async (res) => {
            if (res) {
              let isReturn: boolean = false
              if (modalProTableData && modalProTableData.length > 0) {
                modalProTableData.forEach((item: any) => {
                  if (!item.time) {
                    isReturn = true
                  }
                })
              } else {
                message.error('请在任务详情中,选择稽核时间')
                return
              }
              if (!selectedModalId) {
                message.error('请选择服务区门店')
                return
              }


              if (isReturn) {
                message.error('请选择稽核时间')
                return
              }

              let listId: string = ''
              if (modalProTableData && modalProTableData.length > 0) {
                modalProTableData.forEach((item: any) => {
                  if (listId) {
                    listId += `,${item.time}`
                  } else {
                    listId = item.time
                  }
                })
              }

              const req: any = {
                AUDITTASKS_STARTDATE: res.AUDITTASKS_STARTDATE ? moment(res.AUDITTASKS_STARTDATE).format('YYYY-MM-DD') : '-',
                STAFF_ID: currentUser.ID,
                STAFF_NAME: currentUser.Name,
                AUDITTASKS_DESC: res.AUDITTASKS_DESC,
                STRATTIMES: listId,
                SERVERPARTSHOP_IDS: selectedModalId
              }
              console.log('req', req)
              const data = await handleSynchroAUDITTASKS(req)
              if (data.Result_Code === 100) {
                message.success(data.Result_Desc)
                actionRef.current?.reload()
                setShowModal(false)
                setSelectedModalId(undefined)
                setModalProTableData([])
              } else {
                message.error(data.Result_Desc)
              }
            }
          })
        }}
      >
        <div style={{ width: '100%', height: '650px', backgroundColor: '#fff', display: 'flex' }}>
          <ProCard
            style={{ width: "320px", overflowY: 'scroll' }}
            className="pageTable-leftnav"
            bodyStyle={{ width: "280px" }}
            extra={<MenuFoldOutlined onClick={() => {
              setCollapsible(!collapsible)
            }} />}
            title={!collapsible ? "请选择服务区" : ""}
            headerBordered
            collapsed={collapsible}
          >
            {shopTreeView && shopTreeView.length > 0 ? <Tree
              checkable
              style={{ width: "280px", height: 'calc(100% - 140px)', overflowY: 'auto', overflowX: 'hidden' }}
              treeData={[{
                label: '全部',
                value: 0,
                key: '0-0',
                children: shopTreeView
              }]}
              fieldNames={{
                title: "label",
                key: "key"
              }}
              blockNode
              defaultExpandedKeys={['0-0']}
              onCheck={(checkedKeys: React.Key[] | any, info) => {
                const selectedIds = info.checkedNodes.filter(n => n?.type === 2)
                setSelectedModalId(selectedIds.map(n => n?.value)?.toString() || '')
                // actionRef?.current?.reload()
                // getData(selectedIds.map(n => n?.value)?.toString() || '')
              }}
            // switcherIcon={<PlusOutlined />}
            /> : ''}
          </ProCard>
          <div style={{
            width: !collapsible ? 'calc(100% - 300px)' : 'calc(100% - 60px)',
            paddingTop: '24px',
            paddingBottom: 0,
            paddingRight: 0,
            marginLeft: '16px'
          }}>
            <ProForm
              formRef={modalFormRef}
              submitter={false}
            >
              <div className={'modalTitle'}>基本信息</div>
              <Row>
                <Col span={12}>
                  <ProFormDatePicker
                    style={{ width: '100%' }}
                    label="生效时间"
                    name='AUDITTASKS_STARTDATE'
                    rules={[
                      {
                        required: true,
                        message: '请选择生效时间',
                      },
                    ]}
                  />
                </Col>
                <Col span={24}>
                  <ProFormTextArea
                    label="备注"
                    name="AUDITTASKS_DESC"
                  />
                </Col>
              </Row>
              <div className={'modalTitle'}>任务详情</div>
              <Button onClick={() => {
                const list: any = JSON.parse(JSON.stringify(modalProTableData))
                list.push({ index: modalProTableData.length + 1 })
                setModalProTableData(list)
              }}>添加详情</Button>
              <ProTable
                style={{ width: '320px' }}
                search={false}
                options={false}
                pagination={false}
                columns={modalColumns}
                dataSource={modalProTableData}
              >

              </ProTable>
              <div className={'modalTitle'}>门店详情</div>

            </ProForm>
          </div>
        </div>
      </Modal>


      <Drawer
        width="70%"
        visible={showDetailDrawer} // 抽屉弹框是否显示状态
        onClose={() => { // 关闭抽屉 则在清空选中行数据 并 设置抽屉状态为关闭
          setCurrentRow(undefined);
          setShowDetailDrawer(false);
        }}
        destroyOnClose
        bodyStyle={{ backgroundColor: "#f9f9f9", padding: '24px' }}
        closable={false}
      >
        <ProTable
          actionRef={actionDrawerRef}
          search={false}
          bordered
          columns={drawerColumns}
          request={async () => {
            const req: any = {
              AuditTasksIds: currentRow?.AuditTasksId,
            }
            console.log('req', req)
            const data = await handleGetAuditTasksDetail(req)
            console.log('data', data)
            if (data && data.length > 0) {
              return { data, success: true }
            }
            return { data: [], success: true }
          }}
        >
        </ProTable>
      </Drawer>
    </div>
  )
}

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