// 异常日结处理
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 {
  handleBatchReview,
  handleDailyException,
  handleGetAccountList,
  handleGetServerpartShopList,
  handleGetServiceShopList
} from "@/pages/DataVerification/service";
import './list.less'
import { Button, DatePicker, Select, Drawer, message, Modal, Popconfirm } from "antd";
import useRequest from "@ahooksjs/use-request";
import moment from "moment";
import CheckDetail from "./components/checkDetail";
import ProForm, { ProFormDatePicker, ProFormRadio, ProFormTextArea } from "@ant-design/pro-form";


const List: React.FC<{ currentUser?: CurrentUser }> = ({ currentUser }) => {
  // 详情的ref
  const checkDetail = useRef()
  const modalRef = 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>('')
  // 查询时间
  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 [showModal, setShowModal] = useState<boolean>(false)
  // 悬浮框的显示内容
  const [modalType, setModalType] = useState<number>(0)
  // 选择的表格项
  const [selectTableList, setSelectTableList] = useState<any>()
  // 选中的行
  const [selectedOrderRowKeys, setSelectedOrderRowKeys] = useState<any>()
  // 根据子组件是否出现加载框来判断按钮是否禁用
  const [showDisable, setShowDisable] = useState<boolean>(false)
  const { RangePicker } = DatePicker;
  const rowSelection: any = {
    selectedRowKeys: selectedOrderRowKeys,
    onChange: (selectedRowKeys: any, selectedRows: any) => {
      setSelectTableList(selectedRows)
      console.log('selectedRowKeys', selectedRowKeys)
      setSelectedOrderRowKeys(selectedRowKeys)
    },
  };
  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
          onClick={() => {
            setShowDrawer(true);
            setCurrentRow(record)
          }}
          style={{ color: '#0066FF', textDecoration: 'underline', cursor: 'pointer' }}
        >账期退回</span>
      }
    },
    {
      dataIndex: 'Serverpart_Name',
      title: '服务区名称',
      width: 120,
      ellipsis: true
    },
    {
      dataIndex: 'ServerpartShop_Name',
      title: '门店名称',
      valueType: 'select',
      width: 150,
      ellipsis: true
    },
    {
      dataIndex: 'Description_Info',
      title: '日结校验',
      width: 500,
      ellipsis: true,
      hideInSearch: true,
      render: (_, record) => {
        return <div style={{ width: '450px', 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: '总销售额',
      align: 'right',
      hideInSearch: true,
      render: (_, record) => {
        return <span>{fmoney(record.TotalSell_Amount, 2)}</span>
      }
    },
    {
      dataIndex: 'Difference_Amount',
      title: '长短款',
      align: 'right',
      width: 70,
      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: '实收金额',
      align: 'right',
      hideInSearch: true,
      render: (_, record) => {
        return <span>{fmoney(record.Revenue_Amount, 2)}</span>
      }
    },
    {
      dataIndex: 'Endaccount_EndDate',
      title: '结账日期',
      align: 'center',
      width: 200
    },
    {
      dataIndex: 'Endaccount_State',
      title: '有效状态',
      width: 90,
      valueEnum: {
        1: { text: '有效' },
        0: { text: '无效' }
      },
      render: (_, record) => {
        return <span style={{ color: record.Endaccount_State === 0 ? 'red' : '' }}>{record.Endaccount_State === 1 ? '有效' : record.Endaccount_State === 0 ? '无效' : ''}</span>
      }
    },

  ]
  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)


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

      setSelectShopId(null)
      setShopList(shopList)
    }
    return list
  })
  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'),
      EndaccountState: selectState,
      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)
  }

  const closeModal = () => {
    setShowDrawer(false);
    setShowModal(false)
  }

  // 结账校验详情下方的三个按钮调用的时间
  // 日期账期异常处理的  1保存   2回退   3无效
  const handleError = async (type: number, reason?: string, isBatch?: boolean) => {
    let req = {}
    if (type === 1) {
      let ids: string = ''
      selectTableList.forEach((item: any) => {
        if (ids) {
          ids += `,${item.Endaccount_Id}`
        } else {
          ids = item.Endaccount_Id
        }
      })
      req = {
        OperateType: type,
        EndaccountIds: ids,
        StatisticsDate: reason ? moment(reason).format('YYYY-MM-DD') : ''
      }
    } else {
      if (isBatch) {
        let ids: string = ''
        selectTableList.forEach((item: any) => {
          if (ids) {
            ids += `,${item.Endaccount_Id}`
          } else {
            ids = item.Endaccount_Id
          }
        })
        req = {
          OperateType: type,
          EndaccountIds: ids,
          OperateReason: reason,
        }
      } else {
        req = {
          OperateType: type,
          EndaccountIds: currentRow.Endaccount_Id,
          OperateReason: reason,
        }
      }
    }
    const data = await handleDailyException(req)
    if (data.Result_Code === 100) {
      message.success(data.Result_Desc)
      closeModal()
      handleGetTableList()
    } else {
      message.error(data.Result_Desc)
    }
  }
  const handleChangeShowDisable = (type: boolean) => {
    setShowDisable(type)
  }

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

  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: '' },
              { label: '有效', value: 1 },
              { label: '无效', value: 0 },
              ]}
              onChange={(e) => {
                setSelectState(e)
              }}
            ></Select>
          </div>
          <div className={'searchItem'}>
            <span className={'searchLabel'}>时间：</span>
            <RangePicker
              value={selectTime}
              onChange={(e) => {
                if (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}
          columns={columns}
          bordered
          dataSource={tableData}
          pagination={{ pageSize: 20 }}
          scroll={{ y: 'calc(100vh - 460px)' }}
          rowSelection={{
            type: 'checkbox',
            ...rowSelection,
          }}
          toolbar={{
            actions: [
              <Button
                type="primary"
                onClick={async () => {
                  let isFlag: boolean = true
                  if (selectTableList) {
                    selectTableList.forEach((item: any) => {
                      if (item.Endaccount_State === 0) {
                        isFlag = false
                      }
                    })
                  }
                  if (selectTableList && selectTableList.length > 0 && isFlag) {
                    setModalType(1)
                    setShowModal(true)
                  } else if (!isFlag) {
                    message.error('请检查，选择行中有无效行')
                  }
                  else {
                    message.error('请先选择')
                  }
                }}
              >
                调整日期
              </Button>,
              <Button
                style={{ marginLeft: '8px' }}
                type="primary"
                onClick={async () => {
                  let isFlag: boolean = true
                  if (selectTableList) {
                    selectTableList.forEach((item: any) => {
                      if (item.Endaccount_State === 0) {
                        isFlag = false
                      }
                    })
                  }
                  if (selectTableList && selectTableList.length > 0 && isFlag) {
                    setModalType(2)
                    setShowModal(true)
                  } else if (!isFlag) {
                    message.error('请检查，选择行中有无效行')
                  } else {
                    message.error('请先选择')
                  }
                }}
              >
                异常处理
              </Button>,
            ],
          }}
          onRow={(record) => {
            return {
              // onClick: () => {
              //   setShowDrawer(true);
              //   setCurrentRow(record)
              // },
            }
          }}
        >

        </ProTable>
      </div>

      <Drawer
        width={'60%'}
        visible={showDrawer}
        closable={false}
        bodyStyle={{ padding: 0 }}
        onClose={() => {
          setShowDrawer(false);
        }}
        destroyOnClose={true}
        footer={
          <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
            {
              currentRow?.Treatment_MarkState === 2 || currentRow?.Treatment_MarkState === 3 ?
                <Popconfirm
                  disabled={currentRow?.Endaccount_State === 0}
                  title="确认驳回？"
                  onConfirm={() => {
                    checkDetail.current?.formRef.current?.submit()
                    checkDetail.current?.formRef.current?.validateFields().then(res => {
                      if (res) {
                        handleError(2, res.Review_Info)
                      }
                    })
                  }}
                  okText="确认"
                  cancelText="取消"
                >
                  <Button style={{ marginRight: '8px' }} danger disabled={currentRow?.Endaccount_State === 0 || showDisable}>驳回</Button>
                </Popconfirm> : ''
            }
            {
              currentRow?.Endaccount_State === 1 ?
                <Popconfirm
                  disabled={currentRow?.Endaccount_State === 0}
                  title="确认无效？"
                  onConfirm={() => {
                    checkDetail.current?.formRef.current?.submit()
                    checkDetail.current?.formRef.current?.validateFields().then(res => {
                      if (res) {
                        handleError(3, res.Review_Info)
                      }

                    })
                  }}
                  okText="确认"
                  cancelText="取消"
                >
                  <Button danger style={{ marginRight: '8px' }} disabled={currentRow?.Endaccount_State === 0 || showDisable}>无效</Button>
                </Popconfirm> : ''
            }
            {
              currentRow?.Endaccount_State === 0 ?
                <Button disabled={showDisable} style={{ marginRight: '8px' }} type='primary' onClick={() => {
                  checkDetail.current?.formRef.current?.submit()
                  checkDetail.current?.formRef.current?.validateFields().then(res => {
                    if (res) {
                      handleError(4, res.Review_Info)
                    }
                  })
                }}>有效</Button> : ''
            }
            <Button onClick={() => { setShowDrawer(false) }}>关闭</Button>
          </div>
        }
      >
        <CheckDetail onRef={checkDetail} currentRow={currentRow} currentUser={currentUser} handleGetTableList={handleGetTableList} closeModal={closeModal} handleChangeShowDisable={handleChangeShowDisable} />
      </Drawer>

      <Modal
        title={modalType === 1 ? "调整统计日期" : "异常处理"}
        open={showModal}
        destroyOnClose
        onCancel={() => {
          setShowModal(false)
        }}
        footer={
          modalType === 1 ? [
            <Button onClick={() => {
              setModalType(0)
              setShowModal(false)
            }}>取消</Button>,
            <Button type={'primary'} onClick={() => {
              modalRef.current?.validateFields().then(res => {
                if (res) {
                  handleError(1, res.date)
                }
              })
            }}>保存</Button>
          ] : modalType === 2 ? [
            <Button onClick={() => {
              setModalType(0)
              setShowModal(false)
            }}>取消</Button>,
            <Button type={'primary'} onClick={() => {
              modalRef.current?.validateFields().then(res => {
                if (res) {
                  let isFlag: boolean = true
                  selectTableList.forEach((item: any) => {
                    // 只有待审核 和
                    if (item.Treatment_MarkState < 2) {
                      isFlag = false
                    }
                  })
                  if (isFlag) {
                    handleError(2, res.Review_Info, true)
                  } else {
                    message.error('请检查所选行中状态是否符合要求')
                  }
                }
              })
            }}>驳回</Button>,
            <Button type={'primary'} onClick={() => {
              modalRef.current?.validateFields().then(res => {
                if (res) {
                  let isFlag: boolean = true
                  selectTableList.forEach((item: any) => {
                    if (item.Endaccount_State !== 1) {
                      isFlag = false
                    }
                  })
                  if (isFlag) {
                    handleError(3, res.Review_Info, true)
                  } else {
                    message.error('请检查所选行中状态是否符合要求')
                  }
                }
              })
            }}>无效</Button>] : ''}>
        <ProForm
          formRef={modalRef}
          submitter={{
            // 清空表单自带的按钮
            render: (props, doms) => {
              return []
            }
          }}
        >
          {
            modalType === 1 ?
              <ProFormDatePicker
                name="date"
                label="统计日期"
                rules={[
                  {
                    required: true,
                    message: '请选择统计日期'
                  }
                ]}
              /> : modalType === 2 ?
                <ProFormTextArea
                  label="操作说明"
                  name='Review_Info'
                  rules={[
                    {
                      required: true,
                      message: '请输入操作说明'
                    }
                  ]}
                />
                : ''
          }
        </ProForm>
      </Modal>
    </PageContainer>
  )
}

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