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

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

export default function Page() {
  const [activeTab, setActiveTab] = useState(1)
  const [form] = Form.useForm();
  const [selectData, setSelectData] = useState<any>({
    productName: [],
    publisherType: []
  });
  // 密钥体
  const [tableData, setTableData] = useState([]);
  const [pageNumber, setPageNumber] = useState(1);
  const [pageSize, setpageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  // 配发
  const [tableData1, setTableData1] = useState([]);
  const [pageNumber1, setPageNumber1] = useState(1);
  const [pageSize1, setpageSize1] = useState(10);
  const [total1, setTotal1] = useState(0);
  const [selectedPFKeys, setSelectedPFKeys] = useState([]);
  const [allRowKeys, setAllRowKeys] = useState([]);
  // 执勤
  const [tableData2, setTableData2] = useState([]);
  const [pageNumber2, setPageNumber2] = useState(1);
  const [pageSize2, setpageSize2] = useState(10);
  const [total2, setTotal2] = useState(0);

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

  const columns: any = [
    {
      title: '序号', key: 'index', align: 'center', width: 80,
      render: (a: any, b: any, c: any) => {
        return <span>{(pageNumber - 1) * pageSize + c + 1}</span>;
      },
    },
    { title: '产品名称', dataIndex: 'productName', key: 'productName', align: 'center' },
    { title: '产品编号', dataIndex: 'productNum', key: 'productNum', align: 'center' },
    { title: '载体类型', dataIndex: 'carrierType', key: 'carrierType', align: 'center' },
    { title: '载体型号', dataIndex: 'applyModel', key: 'applyModel', align: 'center' },
    { title: '数量', dataIndex: 'number', key: 'number', align: 'center' },
    { title: '当前状态', dataIndex: 'currentStatus', key: 'currentStatus', align: 'center' },
    { title: '导入时间', dataIndex: 'importTime', key: 'importTime', align: 'center' },
  ]

  const columns1: any = [
    {
      title: '序号', key: 'index', align: 'center', width: 80,
      render: (a: any, b: any, c: any) => {
        return <span>{c + 1}</span>;
      },
    },
    { title: '产品名称', dataIndex: 'productName', key: 'productName', align: 'center' },
    { title: '产品编号', dataIndex: 'productNum', key: 'productNum', align: 'center' },
    { title: '配发管理系统名称', dataIndex: 'distManagerName', key: 'distManagerName', align: 'center' },
    { title: '配发管理系统实体标识', dataIndex: 'distManagerIdentifer	', key: 'distManagerIdentifer', align: 'center' },
    { title: '操作时间', dataIndex: 'name', key: 'name', align: 'center' },
    { title: '同步状态', dataIndex: 'name', key: 'name', align: 'center' }
  ]

  const columns2: any = [
    { title: '执勤区名称', dataIndex: 'name', key: 'name', align: 'center' },
    { title: '执勤区标识', dataIndex: 'name', key: 'name', align: 'center' },
    { title: '所属网络', dataIndex: 'name', key: 'name', align: 'center' },
    { title: 'IP地址', dataIndex: 'name', key: 'name', align: 'center' },
  ]

  useEffect(() => {
    form.setFieldsValue({
      productName: '',
      carrierType: '',
      carrierNumber: '',
      orderDirection: '',
    })
    getSelect()
  }, [])

  // 获取下拉框数据
  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 } });
        setSelectData({
          productName: [{ label: '全部', value: '' }, ...productName]
        })
      } else {
        message.error(res?.errorMsg);
      }
    })
  }

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

  useEffect(() => {
    getList1();
    setSelectedPFKeys([])
  }, [pageNumber1]);


  // 获取密钥体列表
  const getList = () => {
    let data = form.getFieldsValue()
    let params = {
      'secretImport.productName': data.productName,
      'secretImport.productNum': data.productNum,
    }
    secretList({ pageNumber, pageSize, ...params }).then((res) => {
      if (res?.result == "success") {
        setTotal(res.data[0].total);
        setTableData(res.data[0].list);
      } else {
        message.error(res?.errorMsg);
      }
    })
  }

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

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

  const sending = (type: number) => {
    if (selectedRowKeys.length == 0) {
      message.info('请勾选数据');
      return
    }

    let promises = selectedRowKeys.map(item => {
      return secretUpdateStatus({ id: item, type }).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('配发成功');
        pageNumber1 == 1 ? getList1() : setPageNumber1(1);
        setSelectedRowKeys([]);
      }
    });
  }

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

  // 获取向专用密码管理系统配发列表
  const getList1 = () => {
    privateIssueList({ pageNumber: pageNumber1, pageSize: pageSize1 }).then((res) => {
      if (res?.result == "success") {
        setTotal1(res.data[0].total)
        setTableData1(res.data[0].list)
        const keys = res.data[0].list.map((item: any) => item?.id);
        setAllRowKeys(keys);
      } else {
        message.error(res?.errorMsg);
      }
    })
  }

  return (
    <div className={`${styles.params_warp}`}>
      <TabsComp
        dataSource={[{ id: 1, name: '向专用密码管理系统配发密钥体' }]}
        activeTab={activeTab}
        onChange={(e) => setActiveTab(e)} />

      <div style={{ display: 'flex' }}>
        <ButtonComp type={'special'} text={'向专用密码管理系统配发密钥体'} onClick={() => { }} />
      </div>

      <div className='flex_aiC mt20'>

        <Form form={form} layout={'inline'} onFinish={onFinish} className='mt20'>
          {/* <Form.Item name="aaa" label="目的系统" style={formItemSty}>
            <Select style={{ width: 260 }} placeholder={'请选择目的系统'} onChange={(e) => { }} options={[]} />
          </Form.Item> */}
          <Form.Item name="productName" label="产品名称" style={formItemSty}>
            <Select style={{ width: 260 }} placeholder={'请选择产品名称'} onChange={(e) => { }} options={selectData.productName} />
          </Form.Item>
          <div className='flex_aiC'>
            <Form.Item name="productNum" label="产品编号" style={{ marginBottom: 30 }}>
              <Input placeholder="请输入产品编号" style={{ width: 260 }} />
            </Form.Item>
            {/* <ButtonComp style={{ marginBottom: 30 }} text={'添加'} onClick={() => form.submit()} /> */}
            <ButtonComp style={{ marginBottom: 30 }} text={'查询'} onClick={() => form.submit()} />
          </div>
        </Form>
      </div>

      <div className='mb20 flex_aiC_jB'>
        <div>密钥体列表</div>
        <ButtonComp type={'cancel'} text={'配发'} onClick={() => sending(3)} />
      </div>

      <Table
        scroll={{ x: 800, y: 41 * 11 }}
        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 className='mt30 mb20 flex_aiC_jB'>
        <div>配发情况列表</div>
        <ButtonComp type={'cancel'} text={'全部'} onClick={() => {setSelectedPFKeys(allRowKeys)}} />
      </div>

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

      {total1 > 0 && <div className='flex_aiC_jB mt20'>
        <div>共 {total1} 条</div>
        <Pagination
          current={pageNumber1}
          pageSize={pageSize1}
          total={total1}
          showQuickJumper
          onChange={(pageNumber: number) => {
            setPageNumber1(pageNumber);
          }}
          onShowSizeChange={(current: any, pageSize: any) => {
            setpageSize1(pageSize);
            getList1();
          }}
        />
      </div>}

      <div className='mt30 mb20 flex_aiC_jB'>
        <div>执勤列表</div>
        <ButtonComp text={'同步'} onClick={() => { message.info('建设中') }} />
      </div>

      <Table
        scroll={tableData2.length > 0 ? { y: 41 * 5 } : {}}
        pagination={false}
        bordered
        columns={columns2}
        dataSource={tableData2}
        rowKey={(record: any) => record?.id}
        rowClassName={rowClassName}
      />
    </div>
  );
}