import { connect } from "umi";
import type { CurrentUser } from "umi";
import type { ConnectState } from "@/models/connect";
import React, { useEffect, useRef, useState } from "react";
import { PlusOutlined } from "@ant-design/icons";
import type { FormInstance } from "antd";
import { Col } from "antd";
import { Row } from "antd";
import { Button, message, Modal, Popconfirm, Space, Spin, Tree } from "antd";
import useRequest from "@ahooksjs/use-request";
import type { ActionType } from "@ant-design/pro-table";
import ProTable from "@ant-design/pro-table";
import {
  handleCreateUpdateCOMMODITYTYPE, handleDeleteCOMMODITYTYPE,
  handleGetNestingCOMMODITYTYPEList,
  handleGetNestingCOMMODITYTYPETree
} from "@/pages/reports/productControl/commodityType/service";
import ProForm, {
  ProFormDigit, ProFormSelect,
  ProFormSwitch,
  ProFormText,
  ProFormTextArea,
  ProFormTreeSelect
} from "@ant-design/pro-form";
import moment from "moment";
import { handleCallLogs } from "@/services/options";
import './style.less'
import Draggable from "react-draggable";
import PageTitleBox from "@/components/PageTitleBox";

const commodityType: React.FC<{ currentUser: CurrentUser }> = (props) => {
  const { currentUser } = props
  const downloadBtnRef = useRef<any>()
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const modalFormRef = useRef<any>();
  const [reqDetailList, setReqDetailList] = useState<any>(); // 合计项数据源
  const [printOut, setPrintOut] = useState<any>(); // 打印数据的内容
  const [collapsible, setCollapsible] = useState<boolean>(false)
  const [treeView, setTreeView] = useState<any>()
  const [currentRow, setCurrentRow] = useState<any>()
  const [disabled, setDraggleDisabled] = useState<boolean>() // 是否拖动

  // 树相关的属性和方法
  const [selectedId, setSelectedId] = useState<string>()
  // 导出的加载效果
  const [showLoading, setShowLoading] = useState<boolean>(false)
  // 是否显示打印的表格
  const [showExportTable, setShowExportTable] = useState<boolean>(false)
  // 显示新增商品类别
  const [showModal, setShowModal] = useState<boolean>(false)
  const columns: any = [
    {
      title: <div style={{ textAlign: 'center' }}>类别名称</div>,
      dataIndex: 'COMMODITYTYPE_NAME',
      hideInSearch: true,
    },
    {
      title: <div style={{ textAlign: 'center' }}>索引</div>,
      dataIndex: 'COMMODITYTYPE_INDEX',
      align: 'right',
      hideInSearch: true,
    },
    {
      title: <div style={{ textAlign: 'center' }}>类别编码</div>,
      dataIndex: 'COMMODITYTYPE_CODE',
      align: 'right',
      hideInSearch: true,
    },
    {
      title: <div style={{ textAlign: 'center' }}>有效状态</div>,
      dataIndex: 'COMMODITYTYPE_VALID',
      valueType: 'select',
      align: 'center',
      valueEnum: { 0: { text: '无效', status: 'error' }, 1: { text: '有效', status: 'success' }, 2: { text: '不可选', status: 'default' } },
      initialValue: "1"
    },
    {
      title: <div style={{ textAlign: 'center' }}>香烟类别</div>,
      dataIndex: 'CIGARETTE_TYPE',
      valueType: 'select',
      align: 'center',
      hideInSearch: true,
      valueEnum: { 0: { text: '否', status: 'error' }, 1: { text: '是', status: 'success' } },
    },
    {
      title: <div style={{ textAlign: 'center' }}>操作人员</div>,
      dataIndex: 'STAFF_NAME',
      align: 'center',
      hideInSearch: true,
    },
    {
      title: <div style={{ textAlign: 'center' }}>操作时间</div>,
      dataIndex: 'OPERATE_DATE',
      align: 'center',
      hideInSearch: true,
      render: (_, record) => {
        return record?.OPERATE_DATE ? moment(record?.OPERATE_DATE).format('YYYY-MM-DD HH:mm:ss') : '-'
      }
    },
    {
      title: <div style={{ textAlign: 'center' }}>分类说明</div>,
      width: 300,
      ellipsis: true,
      dataIndex: 'COMMODITYTYPE_DESC',
      hideInSearch: true,
    },
    {
      title: <div style={{ textAlign: 'center' }}>操作</div>,
      width: 100,
      valueType: 'option',
      render: (_, record) => {
        return <div>
          <a style={{ marginRight: '8px' }} onClick={() => {
            console.log('record', record)
            setCurrentRow(record)
            setShowModal(true)
          }}>编辑</a>
          <Popconfirm
            title="确认删除？"
            onConfirm={async () => {
              console.log('record', record)
              const req = {
                COMMODITYTYPEId: record?.COMMODITYTYPE_ID
              }
              const data = await handleDeleteCOMMODITYTYPE(req)
              if (data.Result_Code === 100) {
                message.success(data.Result_Desc)
                actionRef.current?.reload()
              } else {
                message.error(data.Result_Desc)
              }
            }}
            okText="确定"
            cancelText="取消"
          >
            <a>删除</a>
          </Popconfirm>
        </div>
      }
    }
  ]

  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-commodityType');                    // 给table添加id，值与按钮上的table字段对应

    container.appendChild(tempTable);                                // 把创建的节点添加到页面容器中

    setShowLoading(false)

    downloadBtnRef.current.handleDownload();
    setShowExportTable(false)
    tempTable.remove() // 防止重复打印一个内容
  }
  // 查询的条件
  const [searchParams, setSearchParams] = useState<any>()
  const draggleRef = React.createRef<any>()
  // 拖动开始
  const [bounds, setBounds] = useState<{ left: number, right: number, top: number, bottom: number }>() // 移动的位置
  const onDraggaleStart = (event, uiData) => {

    const { clientWidth, clientHeight } = window.document.documentElement;
    const targetRect = draggleRef.current?.getBoundingClientRect();
    if (!targetRect) {
      return;
    }
    setBounds({
      left: -targetRect.left + uiData.x,
      right: clientWidth - (targetRect.right - uiData.x),
      top: -targetRect.top + uiData.y,
      bottom: clientHeight - (targetRect.bottom - uiData.y),
    });
  };

  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' }}>
        <div style={{
          width: '100%',
          paddingTop: 0,
          paddingBottom: 0,
          paddingRight: 0
        }}>
          <ProTable
            actionRef={actionRef}
            formRef={formRef}
            columns={columns}
            bordered
            expandable={{
              expandRowByClick: true
            }}
            rowKey='COMMODITYTYPE_ID'
            headerTitle={<PageTitleBox props={props} />}
            // search={false}
            search={{ span: 6 }}
            request={async (params) => {
              const req = {
                ...params,
                PROVINCE_CODE: currentUser?.ProvinceCode,
              }
              setSearchParams(params)
              const data = await handleGetNestingCOMMODITYTYPEList(req)
              console.log('data', data)
              if (data && data.length > 0) {
                setReqDetailList(data)
                return { data, success: true }
              }
              return { data: [], success: true }
            }}
            toolbar={{
              actions: [
                <Button key="button" icon={<PlusOutlined />} type="primary" onClick={() => {
                  setShowModal(true)
                }}>
                  新建
                </Button>
              ]
            }}
          />
        </div>
      </div>

      <Modal
        title={
          <div
            style={{
              width: '100%',
              cursor: 'move',
            }}
            onMouseOver={() => {
              if (disabled) {
                setDraggleDisabled(false)
              }
            }}
            onMouseOut={() => {
              setDraggleDisabled(true)
            }}
            onFocus={() => { }}
            onBlur={() => { }}
          >
            {currentRow ? '编辑商品类别' : '新建商品类别'}
          </div>
        }
        open={showModal}
        destroyOnClose={true}
        width={1000}
        onOk={() => {
          modalFormRef.current?.validateFields().then(async (res: any) => {
            if (res) {
              console.log('res', res)
              let req: any = {}
              if (currentRow) {
                req = {
                  ...currentRow,
                  ...res
                }
              } else {
                req = {
                  COMMODITYTYPE_NAME: res.COMMODITYTYPE_NAME,
                  COMMODITYTYPE_EN: res.COMMODITYTYPE_EN,
                  COMMODITYTYPE_DESC: res.COMMODITYTYPE_DESC,
                  COMMODITYTYPE_VALID: res.COMMODITYTYPE_VALID,
                  CIGARETTE_TYPE: res.CIGARETTE_TYPE,
                  COMMODITYTYPE_PID: res.COMMODITYTYPE_PID,
                  COMMODITYTYPE_INDEX: res.COMMODITYTYPE_INDEX,
                  COMMODITYTYPE_CODE: res.COMMODITYTYPE_CODE,
                  PROVINCE_CODE: currentUser?.ProvinceCode,
                  ADDTIME: res.ADDTIME || moment().format('YYYY-MM-DD HH:mm:ss'),
                  STAFF_ID: currentUser.ID,
                  STAFF_NAME: currentUser.Name,
                  OPERATE_DATE: res.OPERATE_DATE || moment().format('YYYY-MM-DD HH:mm:ss')
                }
              }
              const data = await handleCreateUpdateCOMMODITYTYPE(req)
              console.log('data', data)
              if (data.Result_Code === 100) {
                message.success(data.Result_Desc)
                actionRef.current?.reload()
                setShowModal(false)
                setCurrentRow(undefined)
              } else {
                message.error(data.Result_Desc)
              }
            }
          })
        }}
        onCancel={() => {
          setCurrentRow(undefined)
          setShowModal(false)
        }}
        modalRender={(modal) => {
          return <Draggable
            disabled={disabled}
            bounds={bounds}
            onStart={(event, uiData) => onDraggaleStart(event, uiData)}
          >
            <div ref={draggleRef}>{modal}</div>
          </Draggable>
        }}
      >
        <ProForm
          formRef={modalFormRef}
          submitter={false}
          initialValues={currentRow}
        >
          <Row gutter={32}>
            <Col span={12}>
              <ProFormText
                name='COMMODITYTYPE_NAME'
                label='类别名称'
                rules={[
                  {
                    required: true,
                    message: '请输入类别名称',
                  },
                ]} />
            </Col>
            <Col span={12}>
              <ProFormTreeSelect
                name="COMMODITYTYPE_PID"
                label="上级分类"
                fieldProps={{
                  treeDefaultExpandedKeys: currentRow ? [currentRow?.COMMODITYTYPE_PID] : [-1]
                }}
                initialValue={-1}
                request={async () => {
                  const req = {
                    PROVINCE_CODE: currentUser?.ProvinceCode,
                  }
                  const data = await handleGetNestingCOMMODITYTYPETree(req)
                  const list = [
                    {
                      title: '默认类别',
                      value: -1,
                      type: 0,
                      children: data
                    }
                  ]
                  return list
                }}
                rules={[
                  {
                    required: true,
                    message: '请选择上级分类',
                  },
                ]}>
              </ProFormTreeSelect>
            </Col>
            <Col span={12}>
              <ProFormText
                name='COMMODITYTYPE_CODE'
                label='类别编码'
                rules={[
                  {
                    required: true,
                    message: '请输入类别编码',
                  },
                ]} />
            </Col>
            <Col span={12}>
              <ProFormText
                name='COMMODITYTYPE_EN'
                label='分类简称' />
            </Col>

            <Col span={12}>
              <ProFormDigit
                name="COMMODITYTYPE_INDEX"
                label="商品索引"
                placeholder="请输入商品索引"
                min={0}
                max={9999}
                rules={[
                  {
                    required: true,
                    message: '请输入商品索引',
                  },
                ]}
                fieldProps={{ precision: 0 }}
              />
            </Col>
            <Col span={12}>
              <ProFormSelect
                label="香烟类别"
                name="CIGARETTE_TYPE"
                options={[{ label: '否', value: 0 }, { label: '是', value: 1 }]}
                initialValue={0}
              />
            </Col>
            <Col span={12}>
              <ProFormSelect
                label="是否有效"
                name="COMMODITYTYPE_VALID"
                options={[{ label: '是', value: 1 }, { label: '有效不可选', value: 2 }, { label: '否', value: 0 }]}
                initialValue={1}
                rules={[
                  {
                    required: true,
                    message: '请选择是否有效',
                  },
                ]}
              />
            </Col>
            <Col span={12}>
              <ProFormText
                name='ADDTIME'
                label='添加时间'
                disabled
                initialValue={currentRow?.ADDTIME ? moment(currentRow?.ADDTIME).format('YYYY-MM-DD HH:mm:ss') : moment().format('YYYY-MM-DD HH:mm:ss')}
              />
            </Col>

            <Col span={12}>
              <ProFormText
                name='STAFF_NAME'
                label='操作人员'
                disabled
                initialValue={currentRow?.STAFF_NAME || currentUser.Name}
              />
            </Col>

            <Col span={12}>
              <ProFormText
                name='OPERATE_DATE'
                label='操作时间'
                disabled
                initialValue={currentRow?.OPERATE_DATE ? moment(currentRow?.OPERATE_DATE).format('YYYY-MM-DD HH:mm:ss') : moment().format('YYYY-MM-DD HH:mm:ss')}
              />
            </Col>

            <Col span={24}>
              <ProFormTextArea
                name="COMMODITYTYPE_DESC"
                label="分类说明"
                placeholder="请输入说明" />
            </Col>
          </Row>

        </ProForm>
      </Modal>
    </div>
  )
}

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