import React, { useState, useEffect } from 'react';
import { Card, Input, Space, Form, Select, Button, Steps, Modal, Spin, message, Row } from 'antd';
const { TextArea } = Input;
import { getExamineList, addExamine, getUserInfo, getPowerByRoleId } from './request';
import { useLocation, useNavigate } from 'react-router-dom';
import user from '@/assets/images/user.png';
import userStatus1 from '@/assets/images/user_status1.png';
import userStatus2 from '@/assets/images/user_status2.png';
import userStatus3 from '@/assets/images/user_status3.png';
import defaultUser from '@/assets/images/defaultUser.png';
import { useSelector } from 'react-redux';

import { useGlobalContext } from '../../../layout/GlobalContext';

const AuditDetail = (props) => {
  const { setUnreadMessagesNum } = useGlobalContext();
  const location = useLocation();
  const {
    state: { id },
  } = location;
  const navigate = useNavigate();
  const [current, setCurrent] = useState(0);
  const [examineList, setExamineList] = useState([]);
  const [quanXian, setQuanXian] = useState(true);

  // const [unreadMessagesNum, setUnreadMessagesNum] = useState(0);

  // 获取操作权限
  const { operationPermissionsList } = useSelector((state) => state.user);

  const ExamineList = async () => {
    // const data1 = await getUserInfo();
    // const data2 = await getPowerByRoleId({ role_id: data1.id });
    // if (!data2.includes(154)) {
    //   setQuanXian(true);
    // }

    const data = await getExamineList({ id });
    const totalObjects = data.length; // 计算对象个数

    let arr = data.map((item, index) => {
      const isLastObject = index === totalObjects - 1; // 判断是否为最后一个对象

      return {
        description: <StepCont info={item} />,
        icon: <ImageEl info={item} isLast={isLastObject} />, // 传递 isLast 属性
      };
    });

    setExamineList(arr);
  };
  useEffect(() => {
    ExamineList();
  }, []);

  const StepCont = (itemStep) => {
    const { info } = itemStep;
    let statusColor = '';
    if (info.audit_status === 1) {
      statusColor = 'green';
    } else if (info.audit_status === 2) {
      statusColor = 'red';
    }
    const statusStyle = {
      color: statusColor,
    };
    return (
      <div className=''>
        {quanXian ? (
          <div>
            {info.audit_status === 0 ? (
              <div className=''>
                <strong>{info.user_name ? info.user_name : ''}(提交人)</strong>
                <div className='date'>{info.create_time}</div>
                <div className='status' style={statusStyle}>
                  {info.content}
                </div>
                <div className='infor'>提交信息: {info.release_mess ? info.release_mess : ''}</div>
              </div>
            ) : (
              <div className='audit'>
                <strong>{info.examine_name ? info.examine_name : ''}(审核人)</strong>
                <div className='date'>{info.create_time}</div>
                <div className='status' style={statusStyle}>
                  {info.audit_status_name}
                </div>
                <div className='infor'>审核信息: {info.content ? info.content : ''}</div>
              </div>
            )}

            {/* <div style={{ marginTop: 40 }}>
          <strong>{info.examine_name ? info.examine_name : '空'}(审核人)</strong>
          <div className='infor'>
            审核意见: {info.audit_status_name ? info.audit_status_name : '空'}
          </div>
        </div> */}
          </div>
        ) : null}
      </div>
    );
  };

  const ImageEl = (itemStep) => {
    const { info, isLast } = itemStep;
    let imageSrc;
    let connectorColor;
    if (info.audit_status === 1) {
      imageSrc = userStatus2;
      connectorColor = 'green';
    } else if (info.audit_status === 2) {
      imageSrc = userStatus3;
      connectorColor = 'red';
    } else {
      imageSrc = userStatus1;
      connectorColor = 'gray';
    }
    const containerStyle = {
      position: 'relative', // 相对定位
      height: '100px',
    };

    const connectorStyle = {
      backgroundColor: connectorColor,
      border: `1px solid ${connectorColor}`,
      display: 'flex',
      justifyContent: 'center',
      content: "''",
      position: 'absolute',
      top: '75%',
      left: '50%',
      transform: 'translateY(-50%)',
      height: '50px',
      width: '1px',
      zIndex: '2',
    };

    return (
      <div className=''>
        {quanXian ? (
          <div className='imgel' style={containerStyle}>
            {info.audit_status === 0 ? (
              <div
                className='user'
                style={{
                  backgroundImage: info.user_pic ? `url(${info.user_pic}) ` : `url(${defaultUser})`,
                  backgroundRepeat: 'no-repeat',
                  backgroundSize: '50px 50px',
                  borderRadius: '50%',
                  marginBottom: 50,
                }}
              >
                <img src={imageSrc} className='status'></img>
              </div>
            ) : (
              <div
                className='user'
                style={{
                  backgroundImage: info.examine_pic
                    ? `url(${info.examine_pic}) `
                    : `url(${defaultUser})`,
                  backgroundRepeat: 'no-repeat',
                  backgroundSize: '50px 50px',
                  borderRadius: '50%',
                  marginBottom: 50,
                }}
              >
                <img src={imageSrc} className='status'></img>
              </div>
            )}

            {isLast ? null : <div className='connector' style={connectorStyle}></div>}

            {/* <div
          className='user'
          style={{
            backgroundImage: info.examine_pic ? `url(${info.examine_pic}) ` : `url(${defaultUser})`,
            backgroundRepeat: 'no-repeat',
            backgroundSize: '50px 50px',
            borderRadius: '50%',
          }}
        >
          <img src={imageSrc} className='status'></img>
        </div> */}
            {isLast ? null : <div className='connector' style={connectorStyle}></div>}
          </div>
        ) : null}
      </div>
    );
  };

  const onChange = (value) => {
    console.log('onChange:', value);
    setCurrent(value);
  };
  const [form] = Form.useForm();
  // 获取历史审核
  // const ExamineList = async () => {
  //   const {
  //     state: { id },
  //   } = location;
  //   const data = await getExamineList({ id });
  //   let arr = data.map((item) => ({
  //     description: <StepCont info={item} />,
  //     icon: <ImageEl info={item} />,
  //   }));
  //   setExamineList(arr);
  // };

  const [loading, setLoading] = useState(false);
  const [showModal, setShowModal] = useState(false);
  const [modalMsg, setModalMsg] = useState('');
  const ExamineSure = async (obj) => {
    setLoading(true);
    const {
      data: { check },
      msg,
    } = await addExamine({ id, ...obj });
    setModalMsg(msg);
    let bool = true;
    if (check === 1) {
      setShowModal(true);
      bool = false;
    } else {
      message.success(msg);
      setUnreadMessagesNum(1); // 更新全局状态中的 unreadMessagesNum
    }
    setLoading(false);
    if (!bool) return;
    navigate(-1);
  };

  return (
    <div style={{ padding: 20 }} className='auditdetail'>
      <Modal
        mask={false}
        centered
        open={showModal}
        onOk={() => {
          ExamineSure({ ...form.getFieldsValue(), check: 1 });
          setShowModal(false);
        }}
        onCancel={() => setShowModal(false)}
        footer={(_, { OkBtn, CancelBtn }) => {
          return (
            <Row justify={'center'} className='delModal' style={{ marginBottom: '30px' }}>
              <Space size={20}>
                <CancelBtn className='cancel' />
                <OkBtn className='true' />
              </Space>
            </Row>
          );
        }}
        okText='确认'
      >
        <p style={{ textAlign: 'center', padding: '30px 0 18px', fontSize: 16 }}>{modalMsg}</p>
      </Modal>
      <Spin spinning={loading}>
        <Form onFinish={ExamineSure} form={form} initialValues={{ audit_status: 1 }}>
          <Form.Item
            label='审核状态'
            name='audit_status'
            rules={[{ required: true, message: '请选择审核状态' }]}
          >
            <Select
              placeholder='请选择审核状态'
              style={{ width: 260 }}
              options={[
                { label: '通过', value: 1 },
                { label: '不通过', value: 2 },
              ]}
            ></Select>
          </Form.Item>
          <Form.Item label='审核意见' name='content'>
            <TextArea
              placeholder='请输入审核意见'
              style={{ width: 700 }}
              autoSize={{
                minRows: 6,
                maxRows: 8,
              }}
            ></TextArea>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space size={20} className='footer'>
              <Button
                className='reset'
                onClick={() => {
                  form.setFieldsValue({ audit_status: null, content: '' });
                  form.resetFields();
                }}
              >
                重置
              </Button>
              <Button className='as' htmlType='submit' type='primary'>
                提交
              </Button>
            </Space>
          </Form.Item>
        </Form>

        {operationPermissionsList && operationPermissionsList.includes('/books/audit/getExamineList') && (
          <Card
            className='auditPanel'
            style={{ marginTop: 100, height: '350px', overflow: 'auto' }}
          >
            <Steps
              current={current}
              onChange={onChange}
              direction='vertical'
              items={examineList}
            ></Steps>
          </Card>
        )}
      </Spin>
    </div>
  );
};
export default AuditDetail;
