// 结账数据管理
import React, { useEffect, useRef, useState } from "react";
import type { CurrentUser } from "@/models/user";
import { connect } from "umi";
import type { ConnectState } from "@/models/connect";
import { PageContainer } from "@ant-design/pro-layout";
import ProTable from "@ant-design/pro-table";
import { getEndaccountPhoto, getServerpartOption, handleGetShopTypeTree } from "@/pages/DataVerification/list/service";
import { handleGetAccountList, handleGetServiceShopList, submitEndaccountState } from "@/pages/DataVerification/service";
import './list.less'
import { Button, DatePicker, Select, Drawer, message, Menu } from "antd";
import ProCard from "@ant-design/pro-card";
import useRequest from "@ahooksjs/use-request";
import moment from "moment";
import CheckDetail from "./components/checkDetail";
import { getServerpartTree, handleCallLogs } from "@/services/options";
import { MenuFoldOutlined } from "@ant-design/icons";
import SubMenu from "antd/lib/menu/SubMenu";


const List: React.FC<{ currentUser?: CurrentUser }> = ({ currentUser }) => {
  // 详情的ref
  const checkDetail = useRef()
  // 表格数组
  const [tableData, setTableData] = useState<any>()
  // 选择的服务区
  const [selectServicePartId, setSelectServicePartId] = useState<any>()
  // 门店列表
  const [shopList, setShopList] = useState<any>()
  // 选择的门店列表
  const [selectShopId, setSelectShopId] = useState<any>('')
  // 处理状态
  const [selectState, setSelectState] = useState<any>(3)
  // 异常类型
  const [errorType, setErrorType] = useState<any>('')
  // 经营模式
  const [managerModal, setManagerModal] = useState<any>('')
  // 查询时间
  const [selectTime, setSelectTime] = useState<any>([moment().subtract(1, 'day'), moment().subtract(1, 'day')])
  // 表格的加载效果
  const [tableLoading, setTableLoading] = useState<boolean>(false)
  // 显示抽屉
  const [showDrawer, setShowDrawer] = useState<boolean>(false)
  // 点击 或者双击的当前行数据
  const [currentRow, setCurrentRow] = useState<any>()
  // 根据子组件是否出现加载框来判断按钮是否禁用
  const [showDisable, setShowDisable] = useState<boolean>(false)
  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 [currenMenu, setCurrenMenu] = useState<any>(); // 当前选中左侧菜单的服务区节点

  const { RangePicker } = DatePicker;
  // 格式化金钱的方法
  const fmoney = (s: number, n?: number) => {
    /*
     * 参数说明：
     * s：要格式化的数字
     * n：保留几位小数
     * */
    n = n > 0 && n <= 20 ? n : s.toString().indexOf('.') === -1 ? 0 : s.toString().indexOf('.') > -1 ? s.toString().split('.')[1].length : 2;
    let fuhao = ''; // 如果数字小于零则值为-
    if (s < 0) {
      s = Math.abs(s);
      fuhao = '-'
    }
    s = `${parseFloat((`${s}`).replace(/[^\d\.-]/g, "")).toFixed(n)}`;
    const l = s.split(".")[0].split("").reverse();
    const r = s.split(".")[1];
    let t = "";
    for (let i = 0; i < l.length; i++) {
      t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
    }
    if (n === 0) {
      return s
    }
    return `${fuhao + [...t].reverse().join("")}.${r}`;

  }

  const columns: any = [
    {
      dataIndex: 'key',
      title: '序号',
      width: 50,
      align: 'center',
    },
    {
      dataIndex: 'Treatment_MarkState',
      title: '处理状态',
      width: 90,
      align: 'center',
      render: (_, record) => {
        return <span
          style={{
            color: record.Treatment_MarkState === 0 || record.Treatment_MarkState === 3 ? '#ff6600' : '#000000'
          }}
        >{record.Treatment_MarkState === 0 ? '待处理' :
          record.Treatment_MarkState === 1 ? '待审核' :
            record.Treatment_MarkState === 2 ? '已审结' :
              record.Treatment_MarkState === 3 ? '主任复核' :
                record.Treatment_MarkState === 4 ? '主任审结' : ''}</span>
      }
    },
    {
      dataIndex: 'Serverpart_Name',
      title: '服务区名称',
      ellipsis: true
    },
    {
      dataIndex: 'ServerpartShop_Name',
      title: '门店名称',
      valueType: 'select',
      ellipsis: true,
      width: 250,
    },
    {
      dataIndex: 'Description_Info',
      title: '日结校验',
      width: 600,
      ellipsis: true,
      hideInSearch: true,
      render: (_, record) => {
        return <div style={{ width: '600px', whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden' }}>{
          `${record?.Description_Staff ? `${record?.Description_Staff.split('【')[0]}:` : ''} ${record?.Description_Info}  ${record?.Approved_Staff ? `|${record?.Approved_Staff}:` : ''} ${record?.Approved_Info}`
        }</div>
      }
    },
    {
      dataIndex: 'TotalSell_Amount',
      title: '总销售额',
      width: 100,
      align: 'right',
      hideInSearch: true,
      render: (_, record) => {
        return <span>{fmoney(record.TotalSell_Amount, 2)}</span>
      }
    },
    {
      dataIndex: 'Difference_Amount',
      title: '长短款',
      align: 'right',
      width: 80,
      hideInSearch: true,
      render: (_, record) => {
        return <span style={{ color: Number(record.Difference_Amount) > 0 ? 'green' : Number(record.Difference_Amount) < 0 ? 'red' : '' }}>{fmoney(record.Difference_Amount, 2)}</span>
      }
    },
    {
      dataIndex: 'Revenue_Amount',
      title: '实收金额',
      width: 100,
      align: 'right',
      hideInSearch: true,
      render: (_, record) => {
        return <span>{fmoney(record.Revenue_Amount, 2)}</span>
      }
    },
    {
      dataIndex: 'Endaccount_EndDate',
      title: '结账日期',
      width: 200,
      align: 'center',
    },
  ]
  // 请求服务区的列表的方法 且去掉第一个  的列表数据
  const { loading, data: serviceList } = useRequest(async () => {
    const options = await getServerpartOption()
    const list: any = []
    if (options && options.length > 0) {
      options.forEach((item: any) => {
        if (item.value !== 424) {
          list.push(item)
        }
      })
      // setSelectServicePartId(list[0].value)
    }
    return list
  })
  // 请求表格数据
  const handleGetTableList = async () => {
    setTableLoading(true)
    const req = {
      ServerpartIds: selectServicePartId,
      ServerpartShopCode: selectShopId,
      StartDate: moment(selectTime[0]).format('YYYY-MM-DD'),
      EndDate: moment(selectTime[1]).format('YYYY-MM-DD'),
      // TreatmentMarkState:selectState,
      ExceptionState: 2,
      EndaccountState: 1,
      PageSize: 999999
    }
    handleCallLogs()
    const data = await handleGetAccountList(req)
    if (data && data.List && data.List.length > 0) {
      const list = []
      data.List.forEach((item: any, index: number) => {
        item.key = index + 1
        list.push(item)
      })
      setTableData(list)
    } else {
      setTableData([])
    }
    setTableLoading(false)
  }
  const handleChangeShowDisable = (type: boolean) => {
    setShowDisable(type)
  }
  const getMenuDom = (data: any[], callback: (item: any) => void) => {
    return (data.map((element: any) => {
      // 绑定嵌套树的子节点
      if (element.children && element.children.length > 0) {
        return (
          <SubMenu title={<span>{element.label}</span>}
            icon={element.ico ? <Avatar src={element.ico} size={16} style={{ marginRight: 4 }} shape="square" /> : null}
            key={`${element.key || element.value}`}
            onTitleClick={(item) => {
              // 选中一级菜单
              if (!currenMenu || item.key !== `${currenMenu?.key}`) {
                callback.call(callback, item)
              }
              item.domEvent.stopPropagation();
            }}
          >
            {element.children && element.children.length > 0 && getMenuDom(element.children, callback)}
          </SubMenu>
        )
      }
      return (<Menu.Item icon={element.ico ? <Avatar src={element.ico} size={16} shape="square" /> : null}
        key={`${element.key || element.value}`}>{element.desc && element.desc !== '0/0' ? <><span>{element.label}</span>
          <span style={{ position: 'absolute', right: '10', top: '9px', lineHeight: '20px', padding: '2px 3px' }}>
            [<span style={{ color: 'red' }}>{element.desc.split('/')[0]}</span>/<span style={{ color: '#1890ff' }}>{element.desc.split('/')[1]}</span>]</span></> : element.label}</Menu.Item>)
    }))
  }
  // 主任复核
  // type 0是财务驳回 2是财务审核 3是主任复核
  // desc 是点击审核驳回会出现的必填项
  const handleSubmitEndaccountState = async (type: number, desc: string) => {
    const req = {
      TreatmentMarkState: type,
      EndaccountId: currentRow?.Endaccount_Id,
      RevenueAmount: currentRow?.Revenue_Amount,
      DescriptionStaff: currentUser?.Name,
      DescriptionInfo: desc,
      DescriptionDate: moment().format('YYYY-MM-DD HH:mm:ss')
    }
    const data = await submitEndaccountState(req)
    if (data.Result_Code === 100) {
      message.success(data.Result_Desc)
      setShowDrawer(false);
      handleGetTableList()
    } else {
      message.error(data.Result_Desc)
    }
  }


  const loadSelectedId = (item?: any) => {
    // 选中的子菜单key
    const [type, value] = item.key.split('-')
    if (type === '1') {
      setCurrenMenu(value)
      handleGetShopList(value)
    } else {
      setCurrenMenu('')
    }
  }

  // 拿到该服务区下的门店列表
  const handleGetShopList = async (e: any) => {
    setSelectServicePartId(e)
    const req = {
      ProvinceCode: currentUser?.ProvinceCode,
      ServerpartId: e,
      // ShowWholePower: true
    }
    const data = await handleGetServiceShopList(req)
    setSelectShopId(null)
    console.log('data.Listdata.Listdata.Listdata.List', data.List);

    setShopList(data.List)
  }


  useEffect(() => {
    handleGetTableList()
  }, []);

  return (
    <PageContainer header={{
      title: '',
      breadcrumb: {},
    }}>
      <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}
        >
          {!treeLoading && <Menu
            mode="inline"
            style={{ height: 'calc(100vh - 220px)', overflowY: 'auto', overflowX: 'hidden' }}
            selectedKeys={`1-${currenMenu}`}
            onSelect={(item) => {
              loadSelectedId(item)
            }}
          >
            {getMenuDom(treeViews, loadSelectedId)}
          </Menu>}
        </ProCard>
        <div style={{
          width: !collapsible ? 'calc(100% - 300px)' : 'calc(100% - 60px)',
          paddingTop: 0,
          paddingBottom: 0,
          paddingRight: 0
        }}>
          <div className={'searchBox'}>
            <div className={'searchBoxLeft'}>
              {/* <div className={'searchItem'}> */}
              {/*   <span className={'searchLabel'}>服务区：</span> */}
              {/*   <Select */}
              {/*     style={{minWidth: '150px'}} */}
              {/*     value={selectServicePartId} */}
              {/*     options={serviceList} */}
              {/*     allowClear */}
              {/*     showSearch */}
              {/*     filterOption={(input, option) => */}
              {/*       (option?.label ?? '').toLowerCase().includes(input.toLowerCase()) */}
              {/*     } */}
              {/*     onChange={async (e) => { */}
              {/*       setSelectServicePartId(e) */}
              {/*       const req = { */}
              {/*         ProvinceCode: currentUser?.USER_PROVINCE, */}
              {/*         ServerpartId: e, */}
              {/*         ShowWholePower: true */}
              {/*       } */}
              {/*       const data = await handleGetServiceShopList(req) */}
              {/*       setSelectShopId(null) */}
              {/*       setShopList(data.List) */}
              {/*     }} */}
              {/*   ></Select> */}
              {/* </div> */}
              <div className={'searchItem'}>
                <span className={'searchLabel'}>门店：</span>
                <Select
                  style={{ minWidth: '150px' }}
                  value={selectShopId}
                  allowClear
                  options={shopList}
                  onChange={(e) => {
                    setSelectShopId(e)
                  }}
                ></Select>
              </div>
              {/* <div className={'searchItem'}> */}
              {/*     <span className={'searchLabel'}>处理状态：</span> */}
              {/*     <Select */}
              {/*         style={{minWidth:'150px'}} */}
              {/*         value={selectState} */}
              {/*         allowClear */}
              {/*         options={[{label:'全部',value:''}, */}
              {/*           {label:'待我处理',value:0}, */}
              {/*           {label:'财务审核',value:1}, */}
              {/*           {label:'财务审结',value:2}, */}
              {/*           {label:'主任复核',value:3}, */}
              {/*           {label:'主任审结',value:4}, */}
              {/*         ]} */}
              {/*         onChange={(e)=>{ */}
              {/*             setSelectState(e) */}
              {/*         }} */}
              {/*     ></Select> */}
              {/* </div> */}
              {/* <div className={'searchItem'}> */}
              {/*   <span className={'searchLabel'}>异常类型：</span> */}
              {/*   <Select */}
              {/*     style={{minWidth:'100px'}} */}
              {/*     value={errorType} */}
              {/*     allowClear */}
              {/*     options={[{label:'全部',value:''}, */}
              {/*       {label:'短款日结',value:0}, */}
              {/*       {label:'长款日结',value:1}, */}
              {/*       {label:'异常校验',value:2}, */}
              {/*       {label:'手工录入',value:3}, */}
              {/*       {label:'扫码上传',value:4}, */}
              {/*     ]} */}
              {/*     onChange={(e)=>{ */}
              {/*       setErrorType(e) */}
              {/*     }} */}
              {/*   ></Select> */}
              {/* </div> */}
              <div className={'searchItem'}>
                <span className={'searchLabel'}>经营模式：</span>
                <Select
                  style={{ minWidth: '100px' }}
                  value={managerModal}
                  allowClear
                  options={[{ label: '全部', value: '' },
                  { label: '业主自营', value: 1000 },
                  { label: '合作经营', value: 2000 },
                  { label: '固定租金', value: 3000 },
                  { label: '临时展销', value: 4000 }
                  ]}
                  onChange={(e) => {
                    setManagerModal(e)
                  }}
                ></Select>
              </div>
              <div className={'searchItem'}>
                <span className={'searchLabel'}>时间：</span>
                <RangePicker
                  value={selectTime}
                  onChange={(e) => {
                    setSelectTime([moment(e[0]._d), moment(e[1]._d)])
                  }}
                />
              </div>
            </div>
            <div className={'searchBoxRight'}>
              <Button style={{ marginRight: '8px' }} onClick={async () => {
                setTableLoading(true)
                setSelectServicePartId(null)
                setSelectShopId(null)
                setSelectState(1)
                setSelectTime([moment().subtract(1, 'day'), moment().subtract(1, 'day')])
                const req = {
                  StartDate: moment().subtract(1, 'day').format('YYYY-MM-DD'),
                  EndDate: moment().subtract(1, 'day').format('YYYY-MM-DD'),
                  // TreatmentMarkState:1,
                  EndaccountState: 1,
                  ExceptionState: 2,
                  PageSize: 999999
                }
                handleCallLogs()
                const data = await handleGetAccountList(req)
                if (data && data.List && data.List.length > 0) {
                  const list: any = []
                  data.List.forEach((item: any, index: number) => {
                    item.key = index + 1
                    list.push(item)
                  })
                  setTableData(list)
                } else {
                  setTableData([])
                }
                setTableLoading(false)
              }}>重置</Button>
              <Button type={'primary'} onClick={() => {
                handleGetTableList()
              }}>查询</Button>
            </div>
          </div>
          <div className={'tableBox'}>
            <ProTable
              loading={tableLoading}
              options={false}
              search={false}
              columns={columns}
              dataSource={tableData}
              pagination={{ pageSize: 20 }}
              scroll={{ y: 'calc(100vh - 460px)' }}
              onRow={(record) => {
                return {
                  onClick: () => {
                    setShowDrawer(true);
                    setCurrentRow(record)
                  },
                }
              }}
            >
            </ProTable>
          </div>
        </div>
      </div>
      <Drawer
        width={'60%'}
        visible={showDrawer}
        closable={false}
        bodyStyle={{ padding: 0 }}
        onClose={() => {
          setShowDrawer(false);
        }}
        destroyOnClose={true}
        footer={
          currentRow?.Treatment_MarkState === 3 ?
            <div style={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <Button disabled={showDisable} danger onClick={() => {
                // 调用子组件里面的方法
                checkDetail.current?.handleEndaccountPhoto()
              }}>查看单据</Button>
              <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                <Button disabled={showDisable} style={{ marginRight: '8px' }} type={'primary'} onClick={() => {
                  // 进行表单校验 校验通过之后调用保存的审核方法
                  checkDetail.current.formRef.current?.validateFields().then(res => {
                    if (res) {
                      const desc = checkDetail.current?.handleGetApprovedInfo()
                      handleSubmitEndaccountState(3, desc.Review_Info)
                    }
                  })
                }}>审核</Button>
                <Button onClick={() => {
                  setShowDrawer(false)
                }}>关闭</Button>
              </div>
            </div> : ''
        }
      >
        <CheckDetail onRef={checkDetail} currentRow={currentRow} currentUser={currentUser}
          handleChangeShowDisable={handleChangeShowDisable} />
      </Drawer>
    </PageContainer>
  )
}

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