import TabsComp from '@/components/TabsComp';
import styles from '../../../GLQ/index.less';
import { useEffect, useState } from 'react';
import { ConfigProvider, Form, Pagination, Select, Table, message } from 'antd';

import { rowClassName } from '@/utils';
import ButtonComp from '@/components/ButtonComp';
import { secretFormatList, secretPublisher } from '@/services/my';

export default function Page() {
  const [activeTab, setActiveTab] = useState(1)
  const [tableData, setTableData] = useState([]);
  const [form] = Form.useForm();
  const [pageNumber, setPageNumber] = useState(1);
  const [pageSize, setpageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [selectData, setSelectData] = useState<any>({
    productName: [],
    carrierType: [],
    carrierNumber: [],
    publisherType: []
  });
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [allRowKeys, setAllRowKeys] = useState([]);

  const formItemSty = { width: 'auto', marginBottom: 20, marginRight: 30 };

  useEffect(() => {
    initForm()
    getSelect()
  }, [])


  const initForm = () => {
    form.setFieldsValue({
      productName: '',
      carrierType: '',
      carrierNumber: '',
      publisherType: ''
    })
  }

  // 获取下拉框数据
  const getSelect = () => {
    secretFormatList({}).then((res) => {
      if (res?.result == "success") {
        let list = res.data[0].list;
        let productName = list.map((item: any) => { return { label: item.productName, value: item.productName } });
        let carrierType = list.map((item: any) => { return { label: item.carrierType, value: item.carrierType } });
        let carrierNumber = list.map((item: any) => { return { label: item.carrierNumber, value: item.carrierNumber } });
        let publisherType = list.map((item: any) => { return { label: item.publisherType, value: item.publisherType } });
        setSelectData({
          productName: [{ label: '全部', value: '' }, ...productName],
          carrierType: [{ label: '全部', value: '' }, ...carrierType],
          carrierNumber: [{ label: '全部', value: '' }, ...carrierNumber],
          publisherType: [{ label: '全部', value: '' }, ...publisherType]
        })
      } else {
        message.error(res?.errorMsg);
      }
    })
  }

  useEffect(() => {
    getList();
    setSelectedRowKeys([])
    setAllRowKeys([])
  }, [pageNumber]);

  // 获取密钥体格式列表
  const getList = () => {
    let data = form.getFieldsValue()
    let params = {
      'secretFormat.productName': data.productName,
      'secretFormat.carrierType': data.carrierType,
      'secretFormat.carrierNumber': data.carrierNumber,
      'secretFormat.publisherType': data.publisherType
    }
    secretFormatList({ pageNumber, pageSize, ...params }).then((res) => {
      if (res?.result == "success") {
        setTotal(res.data[0].total)
        setTableData(res.data[0].list)
        const keys = res.data[0].list.map((item: any) => item?.id);
        setAllRowKeys(keys);
      } else {
        message.error(res?.errorMsg);
      }
    })
  }

  const columns: any = [
    {
      title: '序号', key: 'index', align: 'center', width: 80,
      render: (a: any, b: any, c: any) => {
        return <span>{c + 1}</span>;
      },
    },
    { title: '管理系统名称', dataIndex: 'systemName', key: 'systemName', align: 'center' },
    { title: '管理系统实体标识', dataIndex: 'shstemId', key: 'shstemId', align: 'center' },
    { title: '产品名称', dataIndex: 'productName', key: 'productName', align: 'center' },
    { title: '发布状态', dataIndex: 'currentStatus', key: 'currentStatus', align: 'center' },
    { title: '当前状态', dataIndex: 'currentStatus', key: 'currentStatus', align: 'center' },
    { title: '载体类型', dataIndex: 'carrierType', key: 'carrierType', align: 'center' },
    { title: '载体型号', dataIndex: 'carrierNumber', key: 'carrierNumber', align: 'center' }
  ]

  const onFinish = () => {
    pageNumber == 1 ? getList() : setPageNumber(1);
  };

  const pageOnChange = (pageNumber: number) => {
    setPageNumber(pageNumber);
  }

  const onShowSizeChange = (current: any, pageSize: any) => {
    setpageSize(pageSize);
    getList();
  }

  const sending = () => {
    if (selectedRowKeys.length == 0) {
      message.info('请勾选需要发布的数据');
      return
    }

    let promises = selectedRowKeys.map(item => {
      return secretPublisher({ id: item }).then((res) => {
        if (res?.result === "success") {
          return 1;
        } else {
          message.error(res?.errorMsg);
          return 0;
        }
      });
    });

    Promise.all(promises).then(results => {
      let recordCount = results.reduce((acc: any, val) => acc + val, 0);
      
      if (recordCount === selectedRowKeys.length) {
        message.success('发布成功');
        initForm();
        onFinish();
        setSelectedRowKeys([]);
      }
    });
  }

  return (
    <div className={`${styles.params_warp}`}>
      <TabsComp
        dataSource={[{ id: 1, name: '密钥体格式发布' }]}
        activeTab={activeTab}
        onChange={(e) => setActiveTab(e)} />

      <Form form={form} layout={'inline'} onFinish={onFinish} className='mt20'>
        <Form.Item name="productName" label="产品名称" style={formItemSty}>
          <Select style={{ width: 260 }} placeholder="请选择产品名称" onChange={(e) => { }} options={selectData.productName} />
        </Form.Item>
        <Form.Item name="carrierType" label="载体类型" style={formItemSty}>
          <Select style={{ width: 260 }} placeholder="请选择载体类型" onChange={(e) => { }} options={selectData.carrierType} />
        </Form.Item>
        <Form.Item name="carrierNumber" label="载体型号" style={formItemSty}>
          <Select style={{ width: 260 }} placeholder="请选择载体型号" onChange={(e) => { }} options={selectData.carrierNumber} />
        </Form.Item>
        <Form.Item name="publisherType" label="发布方式" style={formItemSty}>
          <Select style={{ width: 260 }} placeholder="请选择发布方式" onChange={(e) => { }} options={selectData.publisherType} />
        </Form.Item>
        {/* <Form.Item name="aaa" label="目的系统" style={formItemSty}>
          <Select style={{ width: 260 }} placeholder="请选择目的系统" onChange={(e) => { }} options={[]} />
        </Form.Item> */}
      </Form>

      <div className='flex_jE' style={{ marginBottom: 30 }}>
        <ButtonComp style={{ marginRight: 20 }} type={'cancel'} text={'发布'} onClick={() => sending()} />
        <ButtonComp text={'查询'} onClick={() => form.submit()} />
      </div>

      <div className='mb20 flex_aiC_jB'>
        <div>发布情况列表</div>
        <ButtonComp type={'cancel'} text={'全部'} onClick={() => setSelectedRowKeys(allRowKeys)} />
      </div>

      <Table
        scroll={tableData.length > 0 ? { y: 41 * 9 } : {}}
        pagination={false}
        bordered
        columns={columns}
        dataSource={tableData}
        rowKey={(record: any) => record?.id}
        rowClassName={rowClassName}
        rowSelection={{
          selectedRowKeys,
          onChange: (selectedKeys: any) => {
            setSelectedRowKeys(selectedKeys);
          }
        }}
      />

      {total > 0 && <div className='flex_aiC_jB mt20'>
        <div>共 {total} 条</div>
        <Pagination
          current={pageNumber}
          pageSize={pageSize}
          total={total}
          showQuickJumper
          onChange={pageOnChange}
          onShowSizeChange={onShowSizeChange}
        />
      </div>}
    </div>
  );
}
