import React, { useRef, useState } from 'react';
import ProTable, { ActionType } from '@ant-design/pro-table';
import { getPage, bizbidaccount, check } from './service';
import { getSessionUserData } from '@/utils/session';
import { Button, Card, Form, Input, message, Modal, Spin } from 'antd';
import ExtendUpload from '@/utils/ExtendUpload';

const layout = {
  labelCol: { span: 7 },
  wrapperCol: { span: 13 },
};

const NoticeList: React.FC<{}> = () => {
  const checkRelationRef = useRef<ActionType>(); //操作数据后刷新列表
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false) //控制模态框是否显示
  const [form] = Form.useForm();
  const [spinning, setSping] = useState<boolean>(false);//加载遮罩

  const columns: any = [
    {
      title: '序号',
      valueType: 'index',
      width: 80
    },
    {
      title: '结算账户',
      dataIndex: 'agencyName',
    },
    {
      title: '商户号',
      dataIndex: 'account',
    },
    {
      title: '证书口令',
      dataIndex: 'password',
    },
    {
      title: '使用标志',
      dataIndex: 'state',
      render: (text: any, record: any) => {
        if (record.state == '0') {
          return (
            <>待验签</>
          )
        } else if (record.state == '1') {
          return (
            <>生效</>
          )
        } else if (record.state == '-1') {
          return (
            <>无效</>
          )
        }
      }
    },
    {
      title: '最近编辑时间',
      dataIndex: 'lastUpdateTime',
      valueType: 'dateTime',
    },
    {
      title: '软证书',
      dataIndex: 'fileId',
      render: (text: any, record: any) => {
        return (
          <ExtendUpload bid={record.fileId} uploadProps={{ name: "file", disabled: true, uploadProps: true }}></ExtendUpload>
        )
      }
    },
    {
      title: '操作',
      render: (text: any, record: any) => {
        if (record.state == '0') {
          return (
            <Button type="link" danger onClick={() => certificateLabel(record.id)}>证书验签</Button>
          )
        } else {
          return (
            <Button type="link" danger disabled>证书验签</Button>
          )
        }
      }
    },
  ]

  const handleOk = () => { // 确认新增
    form.validateFields().then(res => {
      setSping(true);
      const fromData = {
        account: form.getFieldValue("number"),
        password: form.getFieldValue("certificate"),
        fileId: form.getFieldValue("fileId"),
      };
      bizbidaccount(fromData).then(res => {
        if (res.code == 200) {
          setSping(false);
          setIsModalVisible(false)
          message.success('新增成功');
          checkRelationRef.current?.reload();
          form.resetFields()
        } else {
          setSping(false);
          setIsModalVisible(false)
          form.resetFields()
        }
      }).finally(() => {
        setSping(false);
      });;
    })
  }

  const certificateLabel = (id: any) => { // 证书验签
    setSping(true);
    check(id).then(res => {
      if (res.code == 200) {
        setSping(false);
        message.success('证书验签成功！');
        checkRelationRef.current?.reload();
      } else {
        setSping(false);
      }
    });
  }

  return (
    <>
      <Spin spinning={spinning}>
        <Card title="账户信息管理">
          <div className="right-add">
            <Button type="primary" onClick={() => setIsModalVisible(true)}>新增账号信息</Button>
          </div>
          <ProTable
            actionRef={checkRelationRef}
            className="proSearch"
            columns={columns}
            size='small'
            search={false}
            request={async (params) =>
              await getPage(params).then((res) => {
                if (res.code == 200) {
                  let data = res.data;
                  return Promise.resolve({
                    data: data.records,
                    success: res.success,
                    total: res.data.total,
                    current: res.data.current,
                  });
                }
                return Promise.resolve({
                  data: [],
                  success: false,
                  total: 0,
                  current: 1,
                });
              })
            }
            pagination={{ defaultPageSize: 10, showSizeChanger: false }}//默认显示条数
            toolBarRender={false}
          />
        </Card>
        <Modal
          title="新增账户信息"
          visible={isModalVisible}
          onCancel={() => setIsModalVisible(false)}
          footer={[
            <Button onClick={() => handleOk()} loading={spinning}>确 定</Button>,
            <Button onClick={() => (setIsModalVisible(false), form.resetFields())}>取 消</Button>
          ]}
          width={600}
        >
          <Spin spinning={spinning}>
            <Form
              {...layout}
              name="basic"
              form={form}
            >
              <Form.Item
                label="结算账户"
                name="account"
              >
                <Input defaultValue={getSessionUserData().organizationName} />
              </Form.Item>
              <Form.Item
                label="商户号"
                name="number"
                rules={[
                  {
                    required: true,
                    message: '当前项不可为空',
                  },
                ]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                label="证书口令"
                name="certificate"
                rules={[
                  {
                    required: true,
                    message: '当前项不可为空',
                  },
                ]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                label="软证书"
                name="fileId"
                rules={[
                  {
                    required: true,
                    message: '当前项不可为空',
                  },
                ]}
              >
                <ExtendUpload btnName="上传" uploadProps={{ disabled: false }}>
                </ExtendUpload>
                {/* <p className="tip">最大能上传10M</p> */}
              </Form.Item>
            </Form>
          </Spin>
        </Modal>
      </Spin>
    </>
  );
}

export default NoticeList;