// 结账数据校验
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 { getServerpartOption } from "@/pages/DataVerification/list/service";
import {
  handleBatchReview,
  handleGetAccountList,
  handleGetServerpartShopList,
  handleGetServiceShopList,
  submitEndaccountState
} from "@/pages/DataVerification/service";
import './list.less'
import { Button, DatePicker, Select, Drawer, message } from "antd";
import useRequest from "@ahooksjs/use-request";
import moment from "moment";
import CheckDetail from "@/pages/DataVerification/dataExamine/components/checkDetail";
import mobile from '@/assets/DataVerification/mobilePay.png'


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>(1)
  // 查询时间
  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 [selectRowList, setSelectRowList] = useState<any>()
  // 选中的行
  const [selectedOrderRowKeys, setSelectedOrderRowKeys] = useState<any>()
  // 根据子组件是否出现加载框来判断按钮是否禁用
  const [showDisable, setShowDisable] = useState<boolean>(false)

  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 rowSelection: any = {
    selectedRowKeys: selectedOrderRowKeys,
    onChange: (selectedRowKeys: any, selectedRows: any) => {
      setSelectRowList(selectedRows)
      setSelectedOrderRowKeys(selectedRowKeys)
    },
    getCheckboxProps: (record: any) => ({
      disabled: record.Treatment_MarkState !== 1,
    }),
  };


  const columns: any = [
    {
      dataIndex: 'key',
      title: '序号',
      width: 50,
      align: 'center',
    },
    {
      dataIndex: '',
      title: '',
      width: 100,
      align: 'center',
      hideInSearch: true,
      render: (_, record) => {
        return <span style={{
          color: record.Treatment_MarkState === 0 ? 'red' :
            record.Treatment_MarkState === 1 ? '#ff6600' : '#0066FF', fontWeight: 'bold', textDecoration: 'underline', cursor: 'pointer'
        }} onClick={() => {
          setShowDrawer(true);
          setCurrentRow(record)
        }}>
          {record.Treatment_MarkState === 0 ? '未做校验' :
            record.Treatment_MarkState === 1 ? '待您审核' :
              record.Treatment_MarkState === 2 ? '审核原因' :
                record.Treatment_MarkState === 3 ? '主任复核' :
                  record.Treatment_MarkState === 4 ? '主任审结' : ''}
        </span>
      }
    },
    {
      dataIndex: 'Treatment_MarkState',
      title: '处理状态',
      width: 90,
      align: 'center',
      render: (_, record) => {
        return <span
          style={{
            color: record.Treatment_MarkState === 0 ? 'red' :
              record.Treatment_MarkState === 1 ? '#ff6600' : '#0066FF'
          }}
        >{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: '服务区名称',
      width: 120,
    },
    {
      dataIndex: 'ServerpartShop_Name',
      title: '门店名称',
      valueType: 'select',
      ellipsis: true,
      width: 200,
    },
    {
      dataIndex: 'Description_Info',
      title: '日结校验',
      width: 400,
      ellipsis: true,
      hideInSearch: true,
      render: (_, record) => {
        return <div>{
          record.Description_Staff.indexOf('移') === -1 ?
            <span style={{ display: 'inline-block', width: '390px', textOverflow: 'ellipsis', overflow: 'hidden', whiteSpace: 'nowrap' }}>{`${record.Description_Staff ? `${record.Description_Staff}:` : ''} ${record.Description_Info}`}</span>
            :
            <div style={{ display: 'flex', alignItems: 'center', width: '390px', textOverflow: 'ellipsis', overflow: 'hidden', whiteSpace: 'nowrap' }}>
              <img style={{ width: '16px', height: '16px' }} src={mobile} />
              <span>{`${record.Description_Staff.split('【')[0]}: ${record.Description_Info}`}</span>
            </div>

        }</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: '长短款',
      width: 80,
      align: 'right',
      hideInSearch: true,
      render: (_, record) => {
        return <span>{fmoney(record.Difference_Amount, 2)}</span>
      }
    },
    {
      dataIndex: '',
      title: '客单均价',
      width: 80,
      align: 'right',
      hideInTable: true,
      hideInSearch: true,
      render: (_, record) => {
        return <span>{record.Ticket_Count ? (record.TotalSell_Amount / record.Ticket_Count).toFixed(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 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) {
      if (type === 0) {
        message.success('驳回成功！')
      } else {
        message.success(data.Result_Desc)
      }
      setShowDrawer(false);
      handleGetTableList()
    } else {
      message.error(data.Result_Desc)
    }
  }

  const handleGetTableList = async () => {
    const newSelect: any = []
    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,
      EndaccountState: 1,
      PageSize: 999999
    }
    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)
        if (selectedOrderRowKeys && selectedOrderRowKeys.length > 0) {
          if (selectedOrderRowKeys.indexOf(item.Endaccount_Id) !== -1) {
            newSelect.push(item.Endaccount_Id)
          }
        }
      })
      setSelectedOrderRowKeys(newSelect)
      setTableData(list)
    } else {
      setSelectedOrderRowKeys([])
      setTableData([])
    }
    setTableLoading(false)
  }
  useEffect(() => {
    handleGetTableList()
  }, []);
  const handleChangeShowDisable = (type: boolean) => {
    setShowDisable(type)
  }

  return (
    <PageContainer header={{
      title: '',
      breadcrumb: {},
    }}>
      <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)

                const req = {
                  SearchParameter: {
                    SERVERPART_IDS: e,
                    ISVALID: 1
                  },
                  PageIndex: 1,
                  PageSize: 999999,
                  SortStr: "SHOPREGION,SHOPTRADE,SHOPSHORTNAME,SHOPCODE"
                }
                const data = await handleGetServerpartShopList(req)
                console.log('shop', data);
                let list: any = []
                if (data && data.length > 0) {
                  data.forEach((item: any) => {
                    list.push({ label: item.SHOPNAME, value: item.SHOPCODE })
                  })
                }

                setSelectShopId(null)
                setShopList(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: 1 }, { label: '我已审核', value: 2 }]}
              onChange={(e) => {
                setSelectState(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,
              PageSize: 999999
            }
            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)
          }}>重置</Button>
          <Button type={'primary'} onClick={() => {
            handleGetTableList()
          }}>查询</Button>
        </div>
      </div>
      <div className={'tableBox'}>
        <ProTable
          key={'Endaccount_Id'}
          rowKey={'Endaccount_Id'}
          loading={tableLoading}
          options={false}
          search={false}
          rowSelection={{
            type: 'checkbox',
            ...rowSelection,
          }}
          bordered
          columns={columns}
          dataSource={tableData}
          scroll={{ y: 'calc(100vh - 470px)' }}
          pagination={{ pageSize: 20 }}
          toolbar={{
            actions: [
              <Button
                type="primary"
                onClick={async () => {
                  if (selectRowList && selectRowList.length > 0) {
                    const req = []
                    selectRowList.forEach((item: any) => {
                      req.push(item.Endaccount_Id)
                    })
                    const data = await handleBatchReview(req)
                    if (data.Result_Code === 100) {
                      message.success(data.Result_Desc)
                      handleGetTableList()
                    } else {
                      message.error(data.Result_Desc)
                    }
                  } else {
                    message.error('请先选择')
                  }

                }}
              >
                批量审核
              </Button>,
            ],
          }}
          onRow={(record) => {
            return {
              onDoubleClick: () => {
                setShowDrawer(true);
                setCurrentRow(record)
              },
            }
          }}
        >

        </ProTable>
      </div>

      <Drawer
        width={'60%'}
        visible={showDrawer}
        closable={false}
        bodyStyle={{ padding: 0 }}
        onClose={() => {
          setShowDrawer(false);
        }}
        destroyOnClose={true}
        footer={
          currentRow?.Treatment_MarkState === 1 ?
            <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(2, desc.Approved_Info)
                    }
                  })
                }}>审核</Button>
                <Button disabled={showDisable} style={{ marginRight: '8px' }} danger onClick={() => {
                  checkDetail.current.formRef.current?.validateFields().then(res => {
                    if (res) {
                      const desc = checkDetail.current?.handleGetApprovedInfo()
                      handleSubmitEndaccountState(0, desc.Approved_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);
