import { PlusOutlined } from '@ant-design/icons';
import { Modal, Button, message, Input, Popconfirm, Form } 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 QRCode from 'qrcode.react';
import ProDescriptions from '@ant-design/pro-descriptions';
import CreateForm from './components/CreateForm';
import { Getstorestaffpage, Addstorestaff, Updatestorestaff, Delstorestaff, UpdatestorestaffPwd, GetAllStore } from "./services"
const key = 'message';

const GoodsTypeManage = () => {
  /** 新建/更新窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState(false);
  const [pwdModal, setpwdModal] = useState(false);
  /** 分布更新窗口的弹窗 */

  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  const [OrgListArray, setOrgListArray] = useState([]);
  const [storeList, setStoreList] = useState([]);
  /** 国际化配置 */

  //初始化数据
  useEffect(() => {
    onFetchStoreList();
  }, []);

  //获取店铺列表
  const onFetchStoreList = async () => {
    const response = await GetAllStore();
    if (response.statusCode == 200) {
      var list = [];
      response.data.forEach(item => {
        list.push({ id: item.id, text: item.name, value: item.id, label: item.name });
      })
      setStoreList(list);
    } else {
      message.error(response.msg || '获取店铺列表失败');
    }
  }
  //添加
  const handleAdd = async (fields) => {
    try {
      message.loading('正在添加', key);
      await Addstorestaff(JSON.stringify(fields)).then((r) => {
        message.destroy(key);
        if (r.data) {
          message.success('添加成功');
          actionRef.current.reloadAndRest();
          return true;
        } else {
          message.error(r.errors||'添加失败');
          return false;
        }
      });
    } catch (error) {
      message.error('添加失败请重试！');
      return false;
    }
  };


  //修改
  const handleUpdate = async (fields) => {
    try {
      message.loading('正在修改', key);
      message.destroy(key);
      await Updatestorestaff(JSON.stringify(fields)).then((r) => {
        message.destroy(key);
        if (r.data) {
          message.success('修改成功');
          actionRef.current.reloadAndRest();
          return true;
        } else {
          message.error(r.errors||'修改失败');
          return false;
        }
      });
    } catch (error) {
      message.error('修改失败请重试！');
      return false;
    }
  };


  //删除
  const handleRemove = async (ids) => {
    try {
      // message.loading('正在删除');
      await Delstorestaff(ids).then((r) => {
        if (r.data) {
          message.success('删除成功');
          actionRef.current.reloadAndRest();
          return true;
        } else {
          message.error('删除失败');
          return false;
        }
      });
    } catch (error) {
      message.error('删除失败请重试！');
      return false;
    }
  };


  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      hideInSearch: true,
      hideInTable: true,
      tip: '规则名称是唯一的 key'
    },
    {
      title: '名称',
      dataIndex: 'name',
      valueType: 'textarea',
      search: false,

    },
    {
      title: '电话',
      dataIndex: 'phone',
      valueType: 'textarea',
      search: false,
    },
    {
      title: '职工编号',
      dataIndex: 'number',
      valueType: 'textarea',
      search: false,
    },
    {
      title: '归属门店',
      dataIndex: 'shopId',
      ellipsis: true,
      valueType: 'select',
      fieldProps: {
        options: storeList,
      },
      // render: (_, record) => {
      //     const find = storeList.find(item => item.id === record.shopId);
      //     if (find) {
      //       return <div>{find.name}</div>
      //     }
      //   }

    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      search: false,
      valueEnum: {
        0: { text: '正常', status: 'Processing' },
        1: { text: '停用', status: 'Success' },
        2: { text: '删除', status: 'Error' },
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createAt',
      hideInForm: true,
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: 200,
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            handleModalVisible(true);
            setCurrentRow(record);
          }} > 更新</a>,
        <Popconfirm
          key="delete"
          title={`确定要删除吗？`}
          onConfirm={async () => {
            debugger
            await handleRemove([record.id]);
          }}
          okText="确定"
          cancelText="取消"
        >
          <a href="#">删除</a>
        </Popconfirm>,
        <a
          key="config"
          onClick={() => {
            setpwdModal(true);
            record.pwd = "";
            setCurrentRow(record);
          }} > 修改密码</a>
      ],
    },
  ];

  return (
    <PageContainer header={{
      title: '',
      breadcrumb: {},
    }}>
      <ProTable
        pagination={{
          pageSize: 10
        }}
        scroll={{
          x: 1300,
        }}
        headerTitle="店铺类型"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }} >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (params) => {
          var data = [];
          var total = 0;
          await Getstorestaffpage(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
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            删除
          </Button>
          {/* <Button type="primary">批量审批</Button> */}
        </FooterToolbar>
      )}


      <CreateForm
        onFinish={async (value) => {
          var success = false;
          if (value.id) {
            success = handleUpdate(value);
          } else {
            success = handleAdd(value);
          }
          if (success) {
            handleModalVisible(false);
            setCurrentRow(undefined);
            actionRef.current.reloadAndRest();
          }
        }}
        onCancel={() => {
          handleModalVisible(false);
          setCurrentRow(undefined);
        }}
        createModalVisible={createModalVisible}
        storeList={storeList}
        values={currentRow || {}}
      />

      <Modal title="修改密码" open={pwdModal} footer={null}
        onCancel={() => {
          setpwdModal(false);
        }}>
        <Form
          preserve={false}
          onFinish={async () => {
            await UpdatestorestaffPwd(JSON.stringify(currentRow)).then((r) => {
              if (r.data) {
                message.success('修改成功',);
                setpwdModal(false);
              } else {
                message.error(r.errors||'修改失败');
              }
            });
          }}
          initialValues={currentRow}>
          <Form.Item name="id" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item label={"密码"} name="pwd" rules={[{ required: true }]} >
            <Input />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default GoodsTypeManage;
