import { connect } from "umi";
import type { CurrentUser } from "umi";
import type { ConnectState } from "@/models/connect";
import React, { useEffect, useImperativeHandle, useRef, useState } from "react";
import ProCard from "@ant-design/pro-card";
import { MenuFoldOutlined } from "@ant-design/icons";
import type { FormInstance } from "antd";
import { Button, message, Space, Spin, Tree, Tabs } from "antd";
import useRequest from "@ahooksjs/use-request";
import { getServerpartTree } 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 { getUserList, getUserTypeTree } from "@/pages/Setting/Users/service";
import './ChosePlayers.less'
import { getRoleList } from "@/pages/Setting/Roles/service";


// selectRoleTypeId 左侧列选择的id
const ChosePlayers = ({ onRef, defaultPerson, showChosePlayer, currentUser, modalVisible, playerList, selectRoleTypeId }: { playerList: any, defaultPerson: any, onRef: any, showChosePlayer: boolean, currentUser: any, modalVisible: any, selectRoleTypeId?: any }) => {

  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [tableTab, setTableTab] = useState<React.Key>(`${currentUser?.UserPattern}`);
  const selectTab = useRef(`${currentUser?.UserPattern}`)
  // 业主的时候树的数据
  const [treeView, setTreeView] = useState<any>()
  // 供应商的时候树的数据
  const [treeViewSecond, setTreeViewSecond] = useState<any>()
  const [userTypeObj, setUserTypeObj] = useState<any>()
  const { loading: treeLoading, data: treeViews } = useRequest(async () => {
    const req: any = {
      ProvinceCode: currentUser.UserPattern === 2000 ? currentUser.BusinessManID : currentUser.ProvinceCode,
    }
    const data = await getUserTypeTree(req)
    let res: any = []
    if (data && data.length > 0) {
      data.forEach((item: any) => {
        res.push(item)
        if (item.children && item.children.length > 0) {
          item.children.forEach((subItem: any) => {
            res.push(subItem)
            if (subItem.children && subItem.children.length > 0) {
              subItem.children.forEach((thirdItem: any) => {
                res.push(thirdItem)
              })
            }
          })
        }
      })
    }
    console.log('res', res);

    let obj: any = {}
    if (res && res.length > 0) {
      res.forEach((item: any) => {
        obj[item.value] = item.label
      })
    }
    console.log('obj', obj);

    setUserTypeObj(obj)
  })
  // const { loading: treeLoading, data: treeViews } = useRequest(async () => {
  //   // 请求业主的左边那棵树的数据
  //   const req: any = {
  //     SystemRolePattern: 1000,
  //     SYSTEMROLE_TYPE: 2000,
  //     current: 1,
  //     ShowStatus:true,
  //     pageSize: 999999
  //   }
  //   const list = await getRoleList(req)
  //   if (list && list.length>0){
  //     list.forEach((item: any)=>{
  //       item.title = item.SYSTEMROLE_NAME
  //       item.key = item.SYSTEMROLE_ID
  //       if (item.children && item.children.length>0){
  //         item.children.forEach((subItem: any)=>{
  //           subItem.title = subItem.SYSTEMROLE_NAME
  //           subItem.key = subItem.SYSTEMROLE_ID
  //         })
  //       }
  //     })
  //   }
  //   setTreeView(list)
  //   console.log('list',list)
  //   // 请求供应商的左边那棵树的数据
  //   const reqSecond: any = {
  //     ProvinceCode: currentUser?.ProvinceCode,
  //     UserTypePattern:'4000'
  //   }
  //   const data = await getUserTypeTree(reqSecond)
  //   const listSecond: any = []
  //   if (data && data.length>0){
  //     data.forEach((item: any)=>{
  //       item.title = item.label
  //       item.key = item.value
  //       if (item.children && item.children.length>0){
  //         item.children.forEach((subItem: any)=>{
  //           subItem.title = subItem.label
  //           subItem.key = subItem.value
  //         })
  //       }
  //       listSecond.push(item)
  //     })
  //   }
  //   setTreeViewSecond(listSecond)
  // })
  // 选中的行数据
  const [selectModalRowList, setSelectModalRowList] = useState<any>()
  // 选中的行
  const [selectedModalOrderRowKeys, setSelectedModalOrderRowKeys] = useState<any>()
  const [selectedId, setSelectedId] = useState<any>()

  // 供应商选择的左侧列的记录数据
  const [selectedSupplierId, setSelectedSupplierId] = useState<any>()
  const columns: any = [
    {
      title: '查询账号',
      dataIndex: 'searchKey',
      hideInDescriptions: true,
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入账号/用户名称/业主单位/手机号'
      }
    },
    {
      title: '账号',
      dataIndex: 'USER_PASSPORT',
      hideInSearch: true,
    },
    {
      title: '账号部门',
      dataIndex: 'USERTYPE_ID',
      hideInSearch: true,
      valueType: 'select',
      valueEnum: userTypeObj
    },
    {
      title: '用户名称',
      dataIndex: 'USER_NAME',
      hideInDescriptions: true,
      hideInSearch: true,
    },
    {
      title: '有效状态',
      dataIndex: 'USER_STATUS',
      valueType: 'select',
      valueEnum: {
        "1": "有效",
        "0": "无效",
        "": '全部'
      },
      initialValue: "1"
    },
    {
      title: '手机号',
      dataIndex: 'USER_MOBILEPHONE',
      hideInSearch: true
    },
    {
      title: '备注',
      width: 150,
      ellipsis: true,
      dataIndex: 'USER_DESC',
      hideInSearch: true
    },
    // {
    //   title: '业主单位',
    //   dataIndex: 'PROVINCE_UNIT',
    //   hideInSearch: true,
    //   ellipsis:true,
    //   render:(_,record)=>{
    //     return selectTabs==='1000'?record?.PROVINCE_UNIT:selectTabs==='4000'?record?.USER_DESC:''
    //   }
    // },
  ]
  // 业主的时候的选择人
  const modalRowSelection: any = {
    selectedRowKeys: selectedModalOrderRowKeys,
    preserveSelectedRowKeys: true,
    onChange: (selectedRowKeys: any, selectedRows: any) => {
      setSelectedModalOrderRowKeys(selectedRowKeys)
      const list: any = []
      // const result: any = []
      console.log('selectedRows', selectedRows)
      let dataList: any = []
      if (selectModalRowList && selectModalRowList.length > 0) {
        dataList = [...selectModalRowList, ...selectedRows]
      } else {
        dataList = [...selectedRows]
      }
      console.log('dataList', dataList)
      if (dataList && dataList.length > 0) {
        dataList.forEach((item: any) => {
          if (item) {
            list.push({ value: item.value || item.USER_ID, label: item.label || item.USER_NAME })
          }
        })
        console.log('list', list)
        setSelectModalRowList(list)
      }
    },
  };


  const tabItem: any = [
    {
      key: '1000',
      label: '业主',
    },
    {
      key: '4000',
      label: '供应商',
    }
  ]

  const [selectTabs, setSelectTabs] = useState<string>(`${currentUser?.UserPattern}`)

  useEffect(() => {
    console.log('modalVisible', modalVisible)
    if (!modalVisible) {
      setSelectedModalOrderRowKeys([])
    }
  }, [modalVisible])

  useEffect(async () => {
    if (showChosePlayer) {

      // 请求两种树的方法
      // 请求业主的左边那棵树的数据
      const req: any = {
        SystemRolePattern: 1000,
        SYSTEMROLE_TYPE: 2000,
        current: 1,
        ShowStatus: true,
        pageSize: 999999
      }
      const list = await getRoleList(req)
      console.log('listlistlistlistlist', list);

      setTreeView(list)
      // 请求供应商的左边那棵树的数据
      const reqSecond: any = {
        ProvinceCode: currentUser?.ProvinceCode,
        SystemRolePattern: 4000,
        current: 1,
        ShowStatus: true,
        SYSTEMROLE_TYPE: 2000,
        pageSize: 999999
      }
      const data = await getRoleList(reqSecond)
      setTreeViewSecond(data)

      console.log('list', list)
      console.log('data', data)

      // selectRoleTypeId 是该次业务配置人员 一共有几种类 左侧树的数据
      // 先找业主 如果是业主 selectTab 就是1000 不然就是2 只判断第一个
      if (selectRoleTypeId && selectRoleTypeId.length > 0) {
        console.log('selectRoleTypeId', selectRoleTypeId)
        // setSelectedId(selectRoleTypeId)
        let isFirstOver: boolean = false
        if (list && list.length > 0) {
          list.forEach((item: any) => {
            if (selectRoleTypeId.toString().indexOf(String(item.SYSTEMROLE_ID)) !== -1) {
              setSelectedId(selectRoleTypeId)
              setSelectedModalOrderRowKeys(defaultPerson)
              setSelectTabs('1000')
              actionRef.current?.reload()
              isFirstOver = true
            }
            if (item.children && item.children.length > 0) {
              item.children.forEach((subItem: any) => {
                if (selectRoleTypeId.toString().indexOf(String(subItem.SYSTEMROLE_ID)) !== -1) {
                  setSelectedId(selectRoleTypeId)
                  setSelectedModalOrderRowKeys(defaultPerson)
                  setSelectTabs('1000')
                  actionRef.current?.reload()
                  isFirstOver = true
                }
              })
            }
          })
        }
        // 判断是不是已经在业主找到了
        if (isFirstOver) {
          return
        }
        console.log('selectRoleTypeId.toString()', selectRoleTypeId.toString())
        if (data && data.length > 0) {
          data.forEach((item: any) => {
            if (selectRoleTypeId.toString().indexOf(String(item.SYSTEMROLE_ID)) !== -1) {
              setSelectedId(selectRoleTypeId)
              setSelectedModalOrderRowKeys(defaultPerson)
              setSelectTabs('4000')
              actionRef.current?.reload()
            }
            if (item.children && item.children.length > 0) {
              item.children.forEach((subItem: any) => {
                if (selectRoleTypeId.toString().indexOf(String(subItem.SYSTEMROLE_ID)) !== -1) {
                  setSelectedId(selectRoleTypeId)
                  setSelectedModalOrderRowKeys(defaultPerson)
                  setSelectTabs('4000')
                  actionRef.current?.reload()
                }
              })
            }
          })
        }
      }
    }
  }, [showChosePlayer])

  useImperativeHandle(onRef, () => ({
    selectedId,
    selectModalRowList,
    selectedModalOrderRowKeys,
  }));

  return (
    <div style={{ backgroundColor: '#fff', display: 'flex', width: '100%', height: '600px' }}>
      <ProCard
        className="pageTable-leftnav leftHeight"
        style={{ width: "300px", height: '560px' }}
        bodyStyle={{ padding: 0, paddingLeft: 20 }}
      >
        <Tabs
          activeKey={selectTabs}
          items={tabItem}
          onChange={(e: any) => {
            setSelectTabs(e)
            actionRef.current?.reload()
          }}
        />
        {selectTabs && treeView && treeView.length > 0 ? <Tree
          checkable
          treeData={selectTabs === '1000' ? treeView : treeViewSecond}
          // treeData={[{
          //   label: '全部',
          //   value: 0,
          //   key: '0-0',
          //   children: treeView
          // }]}
          fieldNames={{
            title: "SYSTEMROLE_NAME",
            key: "SYSTEMROLE_ID"
          }}
          blockNode
          checkedKeys={selectedId}
          defaultExpandedKeys={selectTabs === '1000' ? [77] : [717]}
          onCheck={(checkedKeys: React.Key[] | any, info) => {
            if (info.checkedNodes && info.checkedNodes.length > 0) {
              const list: any = []
              info.checkedNodes.forEach((item: any) => {
                list.push(item.SYSTEMROLE_ID)
              })
              setSelectedId(list || '')
            } else {
              setSelectedId('')
            }
            // const selectedIds = info.checkedNodes.filter(n => n?.type === 1)
          }}
        /> : ''}
      </ProCard>
      <div style={{
        width: 'calc(100% - 300px)',
        paddingTop: 0,
        paddingBottom: 0,
        paddingRight: 0
      }}>
        {
          showChosePlayer ?
            <div>
              {
                selectTabs === '1000' || selectTabs === '4000' ?
                  <ProTable
                    actionRef={actionRef}
                    formRef={formRef}
                    columns={columns}
                    rowKey="USER_ID"
                    scroll={{ y: '400px' }}
                    className={'choseTableBox'}
                    options={false}
                    pagination={false}
                    request={async (params, sorter) => {
                      if (!selectedId) {
                        return { data: [], success: true }
                      }
                      const sortstr = Object.keys(sorter).map(n => {
                        const value = sorter[n]
                        return value ? `${n} ${value.replace('end', '')}` : ''
                      })
                      const data = await getUserList({
                        ...params,
                        USER_PATTERN: selectTabs,
                        SYSTEMROLE_TYPE: 2000,
                        SYSTEMROLE_IDS: selectedId && selectedId.length > 0 ? selectedId.toString() : selectRoleTypeId && selectRoleTypeId.length > 0 ? selectRoleTypeId.toString() : '',
                        SortStr: sortstr ? sortstr.toString() : 'USER_INDEX',
                        USER_STATUS: params.USER_STATUS,
                        current: 1,
                        pageSize: 999999,
                        keyWord: params.searchKey ? {
                          key: "USER_PASSPORT,USER_NAME,USER_MOBILEPHONE,PROVINCE_UNIT",
                          value: params.searchKey
                        } : null, // 关键词查询
                      })
                      if (data.data && data.data.length > 0) {
                        const list: any = data.data
                        // 默认进来的 先把选择详情的具体行数据拿出来 不然外面没办法回显
                        console.log('data', data)
                        if (defaultPerson && defaultPerson.length > 0) {
                          if (selectModalRowList && selectModalRowList.length > 0) {

                          } else {
                            const detailList: any = []
                            defaultPerson.forEach((item: any) => {
                              list.forEach((subItem: any) => {
                                if (subItem.USER_ID === item) {
                                  detailList.push({ label: subItem.USER_NAME, value: subItem.USER_ID })
                                }
                              })
                            })
                            console.log('detailList', detailList)
                            setSelectModalRowList(detailList)
                          }
                        }
                        return { data: list, success: true }
                      }
                      return { data: [], success: true }
                    }}
                    bordered
                    params={{ USER_PATTERN: tableTab }}
                    rowSelection={showChosePlayer ? {
                      type: "checkbox",
                      ...modalRowSelection,
                    } : false}
                  /> :
                  ''
              }
            </div>
            : ''
        }
      </div>
    </div>
  )
}

export default ChosePlayers
