import React, { useState, useEffect, useMemo } from 'react';
import {
  Table,
  Button,
  Form,
  Divider,
  Modal,
  Popover,
  Input,
  Select,
} from 'antd';
import moment from 'moment';
import styles from './List.less';
import AuthModal from './AuthModal';
import DetailModal from './DetailModal';
import RejectModal from '../WorkingHours/RejectModal';
import { connect } from 'dva';
import { useRequest, useModel } from '@umijs/max';

const { Option } = Select;
//状态
const STATUS = [
  {
    value: 0,
    label: '售前',
  },
  {
    value: 1,
    label: '转执行',
  },
  {
    value: 2,
    label: '转运营',
  },
  {
    value: 3,
    label: '转质保',
  },
];

function Auth(props) {
  const {
    initialState: { user },
  } = useModel('@@initialState');
  const { industryList, typeList, data, flowList, depRole, dispatch, loading } =
    props;
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false);
  const [detailVisible, setDetailVisible] = useState(false);
  const [rejectVisible, setRejectVisible] = useState(false);
  const [currentItem, setCurrentItem] = useState({});
  const columns = [
    {
      title: '项目编号',
      dataIndex: 'project_full_code',
    },
    {
      title: '项目名称',
      dataIndex: 'project_name',
    },
    {
      title: '分类',
      dataIndex: 'TypeInfo',
      render: (TypeInfo) =>
        TypeInfo ? `${TypeInfo.name}(${TypeInfo.code})` : '-',
    },
    /*
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '行业',
      dataIndex: 'IndustryInfo',
      render: IndustryInfo => `${IndustryInfo.name}(${IndustryInfo.code})`,
    },
    {
      title: '所在地',
      dataIndex: 'location',
      render: (location, record) => `${location}(${record.location_code})`,
    },
    {
      title: '期数',
      dataIndex: 'version',
      render: version => `${version}期`,
    },
    */
    {
      title: '流程',
      dataIndex: ['FlowInfo', 'name'],
    },
    {
      title: '状态',
      dataIndex: 'project_status',
      render: (project_status) => {
        // return project_status === 0 ? <>售前</> : <>转执行</>;
        //若添加其他状态则启用以下switch case：
        switch (project_status) {
          case 0:
            return <>售前</>;
          case 1:
            return <>转执行</>;
          case 2:
            return <>转运营</>;
          case 3:
            return <>转质保</>;
        }
      },
    },
    {
      title: '节点',
      dataIndex: 'NodeInfo',
      render: (nodeInfo, item) => {
        let statusDom;
        switch (item.audit_status) {
          case 0:
            statusDom = '待提交';
            break;
          case 1:
            statusDom = <span style={{ color: '#1890ff' }}>审核中</span>;
            break;
          case 2:
            statusDom = (
              <Popover content={`拒绝原因: ${item.audit_comment}`}>
                <span style={{ color: '#f5222d' }}>审核拒绝</span>
              </Popover>
            );
            break;
          case 3:
            statusDom = <span style={{ color: '#a0d911' }}>审核通过</span>;
            break;
        }
        return (
          <>
            {nodeInfo.node}({statusDom})
          </>
        );
      },
    },
    {
      title: '售前项目经理',
      dataIndex: 'AuthorUser',
      render: (AuthorUser) => (AuthorUser ? AuthorUser.CName : '-'),
    },
    {
      title: '创建时间',
      dataIndex: 'c_time',
      render: (c_time) => moment(c_time).format('YYYY.MM.DD'),
    },
    {
      title: '执行经理',
      dataIndex: 'Leader',
      render: (Leader) => (Leader ? Leader.CName : '-'),
    },
    {
      title: '操作',
      render: (record) => (
        <>
          <a
            onClick={() => {
              setCurrentItem(record);
              setDetailVisible(true);
            }}
          >
            项目详情
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => {
              setCurrentItem(record);
              setVisible(true);
            }}
          >
            审核详情
          </a>
        </>
      ),
    },
  ];

  const canAuth = useMemo(() => {
    let { NodeInfo, audit_status, project_status } = currentItem;
    if (!NodeInfo || flowList.length == 0 || depRole.length == 0) return;
    if (audit_status != 1) return;
    let flow = flowList.find((item) => item.id == NodeInfo.flow_id);
    if (!flow) return false;

    if (project_status == 2) return currentItem.opt_manager_id == user.ID;
    if (project_status == 3) return currentItem.wty_manager_id == user.ID;

    let { NodeAudits } = flow.Nodes.find((item) => item.id == NodeInfo.id);

    const role = depRole.find((item) => {
      return NodeAudits.find((audit) => audit.audit_role == item.ID);
    });
    console.log(role);
    return Boolean(role);
  }, [currentItem, flowList, depRole]);

  const queryList = (page) => {
    dispatch({
      type: 'approval/queryAuth',
      payload: {
        currentPage: page.current,
      },
    });
  };

  const onAuth = (type) => {
    if (type == 3) {
      Modal.confirm({
        title: '提示',
        content: '是否确认通过审批?',
        okText: '通过',
        cancelText: '取消',
        onOk() {
          dispatch({
            type: 'approval/authApproval',
            payload: {
              ...currentItem,
              audit_status: 3,
              audit_comment: '',
            },
            callback: () => {
              setVisible(false);
            },
          });
        },
      });
    } else {
      setRejectVisible(true);
    }
  };

  const onReject = ({ desc }) => {
    dispatch({
      type: 'approval/authApproval',
      payload: {
        ...currentItem,
        audit_status: 2,
        audit_comment: desc,
      },
      callback: () => {
        setRejectVisible(false);
        setVisible(false);
      },
    });
  };

  const handleSearch = () => {
    const { projectName, projectCode, projectStatus } = form.getFieldsValue();
    // console.log(error,values);
    let params = {};
    params.project_name = projectName;
    params.project_code = projectCode?.toUpperCase();
    params.project_status = projectStatus;

    dispatch({
      type: 'approval/queryAuth',
      payload: params,
    });
  };

  const renderSearch = () => {
    return (
      <Form
        style={{ marginBottom: 20 }}
        layout="inline"
        initialValues={{
          projectName: null,
          projectCode: null,
          projectStatus: null,
        }}
        form={form}
      >
        <Form.Item label="项目名称" name="projectName">
          <Input style={{ width: 200 }} />
        </Form.Item>
        <Form.Item label="项目编号" name="projectCode">
          <Input style={{ width: 200 }} />
        </Form.Item>
        <Form.Item label="状态" name="projectStatus">
          <Select
            showSearch
            style={{ width: 120 }}
            filterOption={(input, option) =>
              option.props.children
                .toLowerCase()
                .indexOf(input.toLowerCase()) >= 0
            }
          >
            <Option value={null}>全部</Option>
            {STATUS.map((item) => (
              <Option key={item.value}>{item.label}</Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item>
          <Button type="primary" loading={loading} onClick={handleSearch}>
            查询
          </Button>
        </Form.Item>
      </Form>
    );
  };

  useEffect(() => {
    dispatch({
      type: 'approval/queryFlow',
    });
    dispatch({
      type: 'approval/queryAuth',
    });
  }, []);

  useEffect(() => {
    if (!user.ID) return;
    dispatch({
      type: 'user/queryDepRole',
      payload: user,
    });
  }, [user]);

  return (
    <div>
      {renderSearch()}
      <Table
        loading={loading}
        rowKey="id"
        dataSource={data.list}
        pagination={data.pagination}
        columns={columns}
        onChange={queryList}
      />
      <AuthModal
        flowList={flowList}
        visible={visible}
        data={currentItem}
        onClose={() => setVisible(false)}
        onAuth={onAuth}
        canAuth={canAuth}
      />
      <DetailModal
        flowList={flowList}
        visible={detailVisible}
        data={currentItem}
        onClose={() => setDetailVisible(false)}
      />
      <RejectModal
        visible={rejectVisible}
        onOk={onReject}
        onCancel={() => setRejectVisible(false)}
      />
    </div>
  );
}

export default connect(({ approval, user, loading }) => ({
  data: approval.auth,
  typeList: approval.typeList,
  flowList: approval.flowList,
  industryList: approval.industryList,
  depRole: user.depRole,
  loading: loading.models.approval,
}))(Auth);
