import {postActionDetectionGetActionDetectionList} from '@/services/analysis/ActionDetection';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl, useAccess, Access, history } from '@umijs/max';
import {Tag, Image} from 'antd';
import React, { useRef, useState } from 'react';
import VideoModal from "@/pages/Analysis/ActionDetectionList/components/VideoModal";
// import UpdateForm from './components/UpdateForm';
// import CreateForm from "./components/CreateForm";
// import {ColumnDrawer} from "./components/ColumnDrawer";
const ActionDetectionList: React.FC = () => {
      /**
       * @en-US Pop-up window of new window
       * @zh-CN 新建窗口的弹窗
       *  */
      const [videoModalOpen, setVideoModalOpen] = useState<boolean>(false);

      const [createModalOpen, setCreateModalOpen] = useState<boolean>(false);
      /**
       * @en-US The pop-up window of the distribution update window
       * @zh-CN 分布更新窗口的弹窗
       * */
      const [updateModalOpen, setUpdateModalOpen] = useState<boolean>(false);
      const [showDetail, setShowDetail] = useState<boolean>(false);
      /**
       * @en-US International configuration
       * @zh-CN 国际化配置
       * */
      const access = useAccess();
      const intl = useIntl();
      const actionRef = useRef<ActionType>();
      const [currentRow, setCurrentRow] = useState<API.ActionDetection>();
      const [selectedRowsState, setSelectedRows] = useState<API.ActionDetection[]>([]);

      const handleUpdateModal = ()=>{
        if (updateModalOpen) {
          setUpdateModalOpen(false)
          setCurrentRow(undefined)
        } else {
          setUpdateModalOpen(true)
        }
      }
  const handleVideoModal = ()=>{
    if (videoModalOpen) {
      setVideoModalOpen(false)
      setCurrentRow(undefined)
    } else {
      setVideoModalOpen(true)
    }
  }
      const handleCreateModal = ()=>{
        if (createModalOpen) {
          setCreateModalOpen(false)
          setCurrentRow(undefined)
        } else {
          setCreateModalOpen(true)
        }
      }
      const handleColumnDrawer = ()=>{
        if (showDetail) {
          setShowDetail(false)
          setCurrentRow(undefined)
      } else {
          setShowDetail(true)
        }
      }
      const handleDestroy = async (selectedRow: API.ActionDetection) => {
        // deleteActionDetectionDeleteActionDetection({id: selectedRow.id}).then(()=>{
        //   message.success(intl.formatMessage({id: 'common.success', defaultMessage: '$$$'}))
        //   actionRef.current?.reload()
        // }).catch(()=>{
        //   message.error(intl.formatMessage({id: 'common.failure', defaultMessage: '$$$'}))
        // })
      };

const columns: ProColumns<API.ActionDetection>[] = [

  {
    title: (<FormattedMessage
      id="analysis.action_detection.table.list.id"
      defaultMessage="$$$"/>),
    dataIndex: "id",
    hideInSearch: true,
  },

    {
        title: (<FormattedMessage
            id="analysis.action_detection.table.list.source"
            defaultMessage="$$$"/>),
        dataIndex: "source",
        hideInSearch: true,
    },
    {
        title: (<FormattedMessage
            id="analysis.action_detection.table.list.position"
            defaultMessage="$$$"/>),
        dataIndex: "source",
        hideInSearch: true,
        renderText: (text)=>{
            return '工位一'
        }
    },


    {
        title: (<FormattedMessage
            id="analysis.action_detection.table.list.configFile"
            defaultMessage="$$$"/>),
        dataIndex: "configFile",
        hideInSearch: true,
        hideInTable: true,
    },
    {
        title: (<FormattedMessage
            id="analysis.action_detection.table.list.imagesPath"
            defaultMessage="$$$"/>),
        dataIndex: "imagesPath",
        hideInSearch: true,
        valueType: 'image',

        renderText: (text)=>{
          let text_temp = text.replace(/^\.\//, "/");
            return `${FILE_SERVER_HOST}${text_temp}`
        },
        render: (_, record)=>{
          if (record.imagesPath){
            // return <img src={`${FILE_SERVER_HOST}${record.imagesPath.replace(/^\.\//, "/")}`} alt=""/>
            return <Image src={`${FILE_SERVER_HOST}${record.imagesPath.replace(/^\.\//, "/")}`} width={200}/>
          }

        }


    },

    {
        title: (<FormattedMessage
            id="analysis.action_detection.table.list.type"
            defaultMessage="$$$"/>),
        dataIndex: "type",
        hideInSearch: false,
        render: (_, record) => (
          <Tag color={'red'}>{intl.formatMessage({id: `error_type.${record.type}`, defaultMessage: '异常'})}</Tag>
        ),
        valueEnum: {
          playing_phone: {
            text: '玩手机',
            status: 'Error',
          },
          sleep: {
            text:'睡觉',
            status: 'Success',
          },
          person: {
            text: '离岗',
            status: 'Processing',
          },
        },
    },


    {
        title: (<FormattedMessage
            id="analysis.action_detection.table.list.remark"
            defaultMessage="$$$"/>),
        dataIndex: "remark",
        hideInSearch: true,
    },


    {
        title: (<FormattedMessage
            id="analysis.action_detection.table.list.createTime"
            defaultMessage="$$$"/>),
        dataIndex: "timestamp",
        sorter: true,
        hideInSearch: true,
        valueType: 'dateTime',
    },


    {
        title: (<FormattedMessage
            id="analysis.action_detection.table.list.updateTime"
            defaultMessage="$$$"/>),
        dataIndex: "updateTime",
        sorter: true,
        hideInSearch: true,
        valueType: 'dateTime',
    },


        {
            title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
            dataIndex: 'option',
            valueType: 'option',
            fixed:'right',
            render: (_, record) => [
            <Access accessible={access.canUpdate(history.location.pathname)} key={`${history.location.pathname}-add`}>
              <a
                key="video"
                onClick={() => {
                  setVideoModalOpen(true);
                  setCurrentRow(record);
                }}
              >
                <FormattedMessage id="common.open_video" defaultMessage="$$$" />
              </a>
              </Access>
            ],
        },];
return (
        <PageContainer>
          <ProTable<API.ActionDetection>
            headerTitle={intl.formatMessage({
              id: 'pages.searchTable.title',
              defaultMessage: '$$$',
            })}
            options={{ fullScreen: true, setting: true, density: true, reload: true }}
            actionRef={actionRef}
            rowKey="key"
            search={{
              labelWidth: 120,
            }}
            onDataSourceChange={(data)=>{

            }}
            pagination={{
              // showSizeChanger: true,
              pageSize: 10,
            }}
            columnsState={{
              persistenceKey: 'action_detection_list',
              persistenceType: 'localStorage'
            }}
            toolBarRender={() => [
            // <Access accessible={access.canUpdate(history.location.pathname)} key={`${history.location.pathname}-add`}>
            //
            //   <Button
            //     type="primary"
            //     key="primary"
            //     onClick={() => {
            //       setCreateModalOpen(true);
            //     }}
            //   >
            //     <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
            //   </Button>
            // </Access>
            ]}
            request={async (params = {}, sort) => {
            const {current, ...rest} = params
          const reqParams = {
            page: current,
            desc: false,
            orderKey: "",
            ...rest,
          }
          if (sort && Object.keys(sort).length) {
            reqParams.orderKey = Object.keys(sort)[0]
            let sort_select = sort[reqParams.orderKey]
            reqParams.desc = sort_select === 'descend';
          }
          let resp = await postActionDetectionGetActionDetectionList({...reqParams})
          return {
            data: resp.data.list.map((v: API.ActionDetection)=>{
                return {...v, key: v.id}
            }),
            success: resp.success,
            total: resp.data.total,
            current: resp.data.page,
            pageSize: resp.data.pageSize
          };

            }}
            columns={columns}
            // rowSelection={{
            //   onChange: (_, selectedRows) => {
            //     setSelectedRows(selectedRows);
            //   },
            // }}
          />
          {selectedRowsState?.length > 0 && (
            <FooterToolbar
              extra={
                <div>
                  <FormattedMessage id="pages.searchTable.chosen" defaultMessage="Chosen" />{' '}
                  <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
                  <FormattedMessage id="pages.searchTable.item" defaultMessage="$$$" />
                </div>
              }
            >
          {/*    <Button*/}
          {/*  onClick={async () => {*/}
          {/*    deleteActionDetectionDeleteActionDetectionByIds({ids: selectedRowsState.map((v: API.ActionDetection)=>{return v.id as number})}).then(()=>{*/}
          {/*      actionRef.current?.reloadAndRest?.();*/}
          {/*    })*/}
          {/*  }}*/}
          {/*>*/}
          {/*  <FormattedMessage*/}
          {/*    id="pages.searchTable.batchDeletion"*/}
          {/*    defaultMessage="Batch deletion"*/}
          {/*  />*/}
          {/*</Button>*/}
            </FooterToolbar>
          )}
          {/*<CreateForm*/}
          {/*  createModalOpen={createModalOpen}*/}
          {/*  values={currentRow || {}}*/}
          {/*  handleModal={handleCreateModal}*/}
          {/*  reload={actionRef.current?.reload}*/}
          {/*/>*/}
          {/*<UpdateForm*/}
          {/*  updateModalOpen={updateModalOpen}*/}
          {/*  values={currentRow || {}}*/}
          {/*  handleModal={handleUpdateModal}*/}
          {/*  reload={actionRef.current?.reload}*/}
          {/*/>*/}
          <VideoModal modalOpen={videoModalOpen}
                      handleModal={handleVideoModal}
                      values={currentRow || {}}
                      reload={actionRef.current?.reload}
          />

          {/*<ColumnDrawer*/}
          {/*  handleDrawer={handleColumnDrawer}*/}
          {/*  isShowDetail={showDetail}*/}
          {/*  columns={columns}*/}
          {/*  currentRow={currentRow}*/}
          {/*/>*/}

        </PageContainer>
      );
};

    export default ActionDetectionList;
