import { PlusOutlined } from '@ant-design/icons';
import { Modal, Button, message,Popconfirm } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import {
    GetStorePage,
    StoreAdd,
    StoreUpdate,
    StoreDelete,
} from './services';
import { gettree } from '../../org/orgamange/service';
const key = 'message';


const StoreManage = () => {
  const [OrgList, setOrgList] = useState([]);
  //初始化数据
  useEffect(() => {
    gettree().then((r)=>{
      setOrgList(r.data)
    })
  }, []);
  /** 新建/更新窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState(false);
  /** 分布更新窗口的弹窗 */
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  /** 国际化配置 */

  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      hideInSearch: true,
      hideInTable: true,
      tip: '规则名称是唯一的 key',
    },
    {
      title: '场景名称',
      dataIndex: 'name',
    },
    {
      title: '所属组织',
      dataIndex: 'orgName',
      valueType:'treeSelect',
      fieldProps: {
				options: OrgList,
        allowClear:true,
				
			},
      hideInSearch: false,
    },
    {
      title: '电话',
      dataIndex: 'phone',
      search: true,
    },
    {
      title: '排序',
      dataIndex: 'sort',
      search: false,
    },
    {
      title: '描述',
      dataIndex: 'description',
      search: false,
    },

    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: 200,
      render: (_, record) => [
        <a
          key="update"
          onClick={() => {
            handleModalVisible(true);
            setCurrentRow(record);
          }}
        >
          更新
        </a>,
        <Popconfirm
        type="primary"
        key="primary"
        title="确认删除吗？"
        okText="是"
        cancelText="否"
        onConfirm={() => {
           var ids=[{id:record.id}]
           handleRemove(ids);
        }}
        onCancel={() => {}}
      >
        <a href="#">删除</a>
      </Popconfirm>,

      ],
    },
  ];
//添加
const handleAdd = async (fields) => {
  await StoreAdd(JSON.stringify(fields)).then((r) => {
    if (r.succeeded) {
      message.success('添加成功');
      handleModalVisible(false);
      setCurrentRow(undefined);
      actionRef.current.reload();
    } else {
      message.error(r.errors);
    }
  });
 
};
//修改
const handleUpdate = async (fields) => {
 
    await StoreUpdate(JSON.stringify(fields)).then((r) => {

      if (r.succeeded) {
        message.success('修改成功');
        handleModalVisible(false);
        setCurrentRow(undefined);
        actionRef.current.reload();
      } else {
        message.error(r.errors);
      }
    });
  
};

//删除
const handleRemove = async (selectedRows) => {
  
    let ids = [];
    selectedRows.forEach((item) => {
      ids.push(item.id);
    });
    await StoreDelete(ids).then((r) => {
      if (r.succeeded) {
        message.success('删除成功');
        setSelectedRows([]);
        actionRef.current?.reloadAndRest?.();
      } else {
        message.error(r.errors);
      }
    });
};

  return (
    <PageContainer host header={{
      title: '',
      breadcrumb: {},
    }}>
      <ProTable
        headerTitle="场景信息"
        actionRef={actionRef}
        rowKey="id"
        pagination={{ defaultPageSize: 10 }}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (params) => {
          var data = [];
          var total = 0;
          await GetStorePage(params).then((r) => {
            data = r.data.data;
            total = r.data.total;
          });
          return {
            data: data,
            success: true,
            total: total,
          };
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
              {/* <span>
                服务调用次数总计 {selectedRowsState.reduce((pre, item) => pre + item.id, 0)} 万
              </span> */}
            </div>
          }
        >
          {/* <Button type="primary">批量审批</Button> */}
        </FooterToolbar>
      )}

      <CreateForm
        OrgList={OrgList}
        onFinish={async (value) => {
          if (value.id) {
            await handleUpdate(value);
          } else {
            await handleAdd(value);
          }
          
        }}
        onCancel={() => {
          handleModalVisible(false);
          setCurrentRow(undefined);
        }}
        createModalVisible={createModalVisible}
        values={currentRow || {}}
      />

    </PageContainer>
  );
};

export default StoreManage;
