import React, { useState, useEffect } from 'react';
import { Table, Modal, Button, message, Pagination, Tooltip, Space } from 'antd';
import { connect } from 'umi';
import moment from 'moment';

import TopSearch from '../TopSearch';
import HCBGBtn from '../HCBGBtn';
import CK from '@/components/Tabs-CK';
import CXPF from '@/components/Tabs-CXPF';
import BL from '@/components/Tabs-BL';
import PFSPBatch from '@/components/PFSP-Batch';
import BJSPBatch from '@/components/BJSP-Batch';
import PFSP from '@/components/Tabs-PFSP';
import SLGZ from '@/components/Tabs-SLGZ';
import BJSP from '@/components/Tabs-BJSP';
import BJSQ from '@/components/Tabs-BJSQ';
import BJGZ from '@/components/Tabs-BJGZ';
import { getDicsName } from '@/utils/utils';
import { AJZT, BLFS, UserLevel } from '@/utils/constants';
import { getHGIcons, ExampleBar, getTimeLine } from '@/components/MyIcons';

const initDateType = 'sevenDays';
const initSearchParams = {
  page: 1,
  size: 10,
  startTime: moment().add(-7, 'days'),
  endTime: moment(),
};

const TableList = (props) => {
  const { msg, sysToken, refesh, isLocationInBu, type, locationType } = props;
  // debugger;
  const [searchParams, setSearchParams] = useState(initSearchParams);
  const [tableData, setTableData] = useState(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  const [nowModal, setNowModal] = useState(null);

  const rowSelection = {
    selectedRowKeys,
    onChange: (keys, rows) => {
      setSelectedRows(rows)
      setSelectedRowKeys(keys);
    },
    // getCheckboxProps: (record) => ({
    //   disabled: record.ajhczbl === 0,
    // }),
  };

  const handleClearCheck = () => {
    setSelectedRowKeys([]);
    setSelectedRows([]);
  };

  const getList = (params) => {
    handleClearCheck();
    const newParams = isLocationInBu && type === 'sheng' ? { ...params, sign: 1 } : params; // 部里发布 并且查询省里的列表加额外参数
    // debugger;
    const newSysToken = (locationType === UserLevel.Province.value && type === 'sheng')|| (locationType === UserLevel.City.value && type === 'shi') ? '' : sysToken;
    props.fetchDoingList({ params: newParams, sysToken:newSysToken }).then((data) => setTableData(data));
  };

  const hideModal = (flag) => {
    setNowModal(null);
    if (flag) {
      props.setRefresh(Math.random()); // 更新modal里的监测数据，为了刷新右上角消息
      getList(searchParams);
    }

  };

  const changeModal = (newComponent, flag) => {
    setNowModal(newComponent);
    if (flag) {
      getList(searchParams);
    }
  };

  const reBJSP = (record) => {
    setNowModal(
      <BJSP id={record.id} sysToken={sysToken} hideModal={hideModal} />,
    );
  };

  const reBJSQ = (record) => {
    setNowModal(
      <BJSQ id={record.id} sysToken={sysToken} hideModal={hideModal} />,
    );
  };

  const onclickReBJCheck = (record, modalType) => {
    props.fetchReBJCheck({ params: record.id, sysToken }).then((res) => {
      if (res.data) {
        if (modalType === 'sp') reBJSP(record);
        if (modalType === 'sq') reBJSQ(record);
        getList(searchParams); // 状态更改 要刷新列表
      } else {
        message.warning('不！');
      }
    });
  };

  // ck --查看--按钮是否显示  0-否 1-是
  // slpf -- 受理派发 --按钮是否显示 0-否 1-是
  // sldspgz 受理待审批--跟踪--按钮是否显示  0-否 1-是
  // sldspsp 受理待审批--审批--按钮是否显示  0-否 1-是
  // slbbhcxsq 受理被驳回--重新申请 按钮是否显示  0-否 1-是
  // ajhczbl 案件核查中--办理--按钮是否显示  0-否 1-是
  // bjdspgz 办结待审批--跟踪--按钮是否显示  0-否 1-是
  // bjdspsp 办结待审批--审批--按钮是否显示  0-否 1-是"
  // bjbbhcxsq 办结被驳回--重新申请--按钮是否显示  0-否 1-是
  // bjbbhcxsp 办结被驳回--重新审批--按钮是否显示  0-否 1-是

  const renderBtn = (record) => {
    const { id } = record;
    const allBtns = [];
    // const all = ['ck', 'sldspgz'];
    const ck = (
      <Button
        key='ck'
        type="link"
        onClick={() => setNowModal(<CK id={id} info={record} sysToken={sysToken} />)}
      >
        查看
      </Button>
    );
    const slpf = (
      <Button
        key='slpf'
        type="link"
        onClick={() => setNowModal(<CXPF id={id} sysToken={sysToken} hideModal={hideModal} />)}
      >
        受理派发
      </Button>
    );
    const sldspgz = (
      <Button
        key='sldspgz'
        type="link"
        onClick={() => setNowModal(<SLGZ id={id} sysToken={sysToken} hideModal={hideModal} />)}
      >
        跟踪
      </Button>
    );
    const sldspsp = (
      <Button
        key='sldspsp'
        type="link"
        onClick={() => setNowModal(<PFSP id={id} sysToken={sysToken} hideModal={hideModal} />)}
      >
        审批
      </Button>
    );
    const slbbhcxsq = (
      <Button
        key='slbbhcxsq'
        type="link"
        onClick={() => setNowModal(<CXPF id={id} sysToken={sysToken} hideModal={hideModal} />)}
      >
        重新申请
      </Button>
    );
    const ajhczbl = (
      <Button
        key='ajhczbl'
        type="link"
        onClick={() =>
          setNowModal(
            <BL id={id} sysToken={sysToken} hideModal={hideModal} changeModal={changeModal} />,
          )
        }
      >
        办理
      </Button>
    );
    const bjdspgz = (
      <Button
        key='bjdspgz'
        type="link"
        onClick={() => setNowModal(<BJGZ id={id} sysToken={sysToken} hideModal={hideModal} />)}
      >
        跟踪
      </Button>
    );
    const bjdspsp = (
      <Button
        key='bjdspsp'
        type="link"
        onClick={() =>
          setNowModal(
            <BJSP id={id} sysToken={sysToken} hideModal={hideModal} changeModal={changeModal} />,
          )
        }
      >
        审批
      </Button>
    );
    const bjbbhcxsq = (
      <Button key='bjbbhcxsq' type="link" onClick={() => onclickReBJCheck(record, 'sq')}>
        重新申请
      </Button>
    );
    const bjbbhcxsp = (
      <Button key='bjbbhcxsp' type="link" onClick={() => onclickReBJCheck(record, 'sp')}>
        重新审批
      </Button>
    );
    // debugger;
    if (record.ck === 1) allBtns.push(ck);
    if (record.slpf === 1) allBtns.push(slpf);
    if (record.sldspgz === 1) allBtns.push(sldspgz);
    if (record.sldspsp === 1) allBtns.push(sldspsp);
    if (record.slbbhcxsq === 1) allBtns.push(slbbhcxsq);
    if (record.ajhczbl === 1) allBtns.push(ajhczbl);
    if (record.bjdspgz === 1) allBtns.push(bjdspgz);
    if (record.bjdspsp === 1) allBtns.push(bjdspsp);
    if (record.bjbbhcxsq === 1) allBtns.push(bjbbhcxsq);
    if (record.bjbbhcxsp === 1) allBtns.push(bjbbhcxsp);
    // all.forEach(item => {
    //   if (record[item] === 1) {
    //     console.log('ppsp',[item.toUpperCase()])
    //     allBtns.push([item.toUpperCase()])
    //   };
    // })
    // debugger
    return allBtns;
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      render: (text, record, index) => index + 1,
      width: '5%',
    },
    {
      title: '预警编号',
      dataIndex: 'yjBh',
      width: '24%',
      render: (text, record) => {
        return (<span>{getHGIcons(record?.ccjg)}{text}</span>);
      }
    },
    {
      title: '模型名称',
      dataIndex: 'mxMc',
      width: '8%',
      render: text => (<Tooltip placement="topLeft" title={text} >{text}</Tooltip>),
      ellipsis: { showTitle: false },
    },
    {
      title: '问题类型',
      dataIndex: 'cjwtLx',
      width: '8%',
      render: text => (<Tooltip placement="topLeft" title={text} >{text}</Tooltip>),
      ellipsis: { showTitle: false },
    },
    {
      title: '承办督察部门',
      dataIndex: 'sadwMc',
      width: '9%',
      render: text => (<Tooltip placement="topLeft" title={text} >{text}</Tooltip>),
      ellipsis: { showTitle: false },
    },
    {
      title: '办理方式',
      dataIndex: 'nbfs',
      width: '7%',
      render: text => (<Tooltip placement="topLeft" title={getDicsName(BLFS, text)} >{getDicsName(BLFS, text)}</Tooltip>),
      ellipsis: { showTitle: false },
    },
    {
      title: '问题简述',
      dataIndex: 'wtjs',
      width: '7%',
      render: text => (<Tooltip placement="topLeft" title={text} >{text}</Tooltip>),
      ellipsis: { showTitle: false },
    },
    {
      title: '当前办理单位',
      dataIndex: 'dqbldwMc',
      width: '12%',
      render: text => (<Tooltip placement="topLeft" title={text} >{text}</Tooltip>),
      ellipsis: { showTitle: false },
    },
    {
      title: '当前办理人',
      dataIndex: 'dqblrMc',
      width: '9%',
      render: text => (<Tooltip placement="topLeft" title={text} >{text}</Tooltip>),
      ellipsis: { showTitle: false },
    },
    {
      title: '预警流向',
      dataIndex: 'blfsMc',
      width: '7%',
      render: text => (<Tooltip placement="topLeft" title={text} >{text}</Tooltip>),
      ellipsis: { showTitle: false },
    },
    {
      title: '最新状态',
      dataIndex: 'dqZt',
      width: '7%',
      // render: (text) => getDicsName(AJZT, text),
      render: text => (<Tooltip placement="topLeft" title={getDicsName(AJZT, text)} >{getDicsName(AJZT, text)}</Tooltip>),
      ellipsis: { showTitle: false },
    },
    {
      title: '最新更新时间',
      dataIndex: 'updateTime',
      width: '9%',
      render: text => (<Tooltip placement="topLeft" title={text} >{text}</Tooltip>),
      ellipsis: { showTitle: false },
    },
    {
      title: '最迟反馈时间',
      dataIndex: 'zcfkSj',
      width: '9%',
      render: text => (<Tooltip placement="topLeft" title={text} >{text}</Tooltip>),
      ellipsis: { showTitle: false },
    },
    {
      title: '时限',
      key: 'id',
      dataIndex: 'fkyj',
      width: '5%',
      render: (text) => getTimeLine(text),
      // fixed: 'right',
    },
    {
      title: '操作',
      dataIndex: 'id',
      width: '12%',
      render: (text, record) => {
        console.log(record, 999)
        return renderBtn(record);
      },
      fixed: 'right',
    },

  ];

  useEffect(() => { // 列表正常请求
    if (!msg) {
      getList(searchParams);
    }
  }, [refesh]);

  useEffect(() => { // 点击待办跳转过来的，参数由跳转带过来
    if (msg) {
      setSearchParams(msg);
      getList(msg);
    }
  }, [msg]);

  // 点击查询
  const onSearch = (params) => {
    setSearchParams({ ...searchParams, ...params, page: 1 });
    getList({ ...searchParams, ...params, page: 1 });
  };

  const handleReset = () => {
    setSearchParams(initSearchParams);
    getList(initSearchParams);
  };

  const changePage = (page) => {
    setSearchParams({ ...searchParams, page });
    getList({ ...searchParams, page });
  };


  const checkBatch = (dqzt, nowType) => {
    if (selectedRows.length === 0) {
      message.warning('请选择办理案件！');
      return false;
    }
    const Nbfs = selectedRows[0].nbfs;
    const Blfs = selectedRows[0].blfs;
    let showPFSPRows = [];
    if (selectedRows.every((item) => item.dqZt === dqzt || AJZT.BJDSP.value && item.nbfs !== null && item.nbfs === Nbfs  && item.nbfs !== null && item.nbfs === Nbfs  && item.blfs !== null && item.blfs === Blfs )) {
      if (nowType === 'sp') { // 批量审批
        selectedRows.map(item => {
          if (item.sldspsp || item.bjdspsp) {
            showPFSPRows.push(item.id);
          }
        });
        if (showPFSPRows.length === selectedRows.length) {
          setNowModal(<PFSPBatch ids={showPFSPRows} batchNbfs={Nbfs}  sysToken={sysToken} hideModal={hideModal} />)
        } else {
          message.warning('选择的案件中有不可审批的案件，无法批量审批！')
        }
      } else if (nowType === 'bj') { // 批量办结
        setNowModal(<BJSPBatch ids={selectedRowKeys} batchNbfs={Nbfs}  sysToken={sysToken} hideModal={hideModal} />)
      }
    } else {
      message.warning('请选择对应且相同状态下办理方式统一案件进行批量处理！')
    }

  }

  return (
    <div>
      {/* <p>{props.a}</p> */}
      <TopSearch
        onSearch={onSearch}
        initDateType={initDateType}
        // initParams={{ mxmc: 111 }}
        changeParams={msg}
        handleReset={handleReset}
      />
      <div style={{ textAlign: 'right', padding: 10, backgroundColor: '#fff', paddingRight: 20 }}>
        <Space>
          {/* <Button>批量受理派发</Button> */}
          <Button type='primary' onClick={() => checkBatch(AJZT.SLDSP.value, 'sp')}>批量受理审批</Button>
          {/* <Button>批量办结审批</Button> */}
          <HCBGBtn
            sysToken={sysToken}
            ids={selectedRowKeys}
            selectedRowKeys={selectedRows}
            handleClearCheck={handleClearCheck}
          />
        </Space>
      </div>
      <Table
        columns={columns}
        dataSource={tableData?.records}
        rowKey="id"
        rowSelection={rowSelection}
        scroll={{ x: 1820 }}
        loading={props.loading}
        pagination={false}
      // current: tableData?.current,
      // pageSize: tableData?.size,
      // total: tableData?.total,
      // onChange: (page) => changePage(page),
      // showSizeChanger: true,
      // onShowSizeChange: () => this.onShowSizeChange,
      // pageSizeOptions: ['10', '20', '50', '100', '500', '1000'],

      />
      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
        <ExampleBar />
        <Pagination
          current={tableData?.current || 0}
          pageSize={tableData?.size || 0}
          total={tableData?.total || 0}
          onChange={page => changePage(page)}
          showTotal={(total) => `共 ${total} 条`}
        />
      </div>
      {nowModal && (
        <Modal
          visible={nowModal}
          footer={null}
          onCancel={() => setNowModal(null)}
          maskClosable={false}
          width={1200}
        // style={{ height: 'calc(100vh - 100px)' , top: 50, overflowY: 'auto' }}
        >
          {nowModal}
        </Modal>
      )}
    </div>
  );
};

const mapStateToProps = ({ user, doing, loading }) => ({
  user: user.currentUser,
  doing,
  loading:
    loading.effects['doing/fetchDoingList'] || loading.effects['doing/fetchReBJCheck'] || false,
});
const mapDispatchToProps = (dispatch) => ({
  // 列表
  fetchDoingList({ params, sysToken }) {
    const chooseTime = {};
    if (params.startTime)
      chooseTime.startTime = `${params.startTime.format('YYYY-MM-DD')} 00:00:00`;
    if (params.endTime) chooseTime.endTime = `${params.endTime.format('YYYY-MM-DD')} 23:59:59`;
    return dispatch({
      type: 'doing/fetchDoingList',
      payload: { params: { ...params, ...chooseTime }, sysToken },
    });
  },
  fetchReBJCheck(params) {
    return dispatch({ type: 'doing/fetchReBJCheck', payload: params });
  },
  setRefresh(params) {
    return dispatch({ type: 'doing/setRefresh', payload: params });
  }
});
export default connect(mapStateToProps, mapDispatchToProps)(TableList);
