import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Form,
  Select,
  Divider,
  Modal,
  Popover,
  Input,
  Checkbox,
} from 'antd';
import moment from 'moment';
import styles from './List.less';
import ApprovalModal from './ApprovalModal';
import DetailModal from './DetailModal';
import ExecutionModal from './ExecutionModal';
import MemberModal from './MemberModal';
import QualityOperateModal from './QualityOperateModal';
import BudgetModal from './BudgetModal';
import ModifyManagerModal from './ModifyManagerModal';
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 List(props) {
  const {
    initialState: { user },
  } = useModel('@@initialState');
  const {
    industryList,
    typeList,
    data,
    flowList,
    dispatch,
    loading,
    depUserTree,
    member,
    budget,
  } = props;
  const [form] = Form.useForm();
  const [addVisible, setAddVisible] = useState(false);
  const [detailVisible, setDetailVisible] = useState(false);
  const [executionVisible, setExecutionVisible] = useState(false);
  const [qualityOperateVisible, setQualityOperateVisible] = useState(false);
  const [memberVisible, setMemberVisible] = useState(false);
  const [budgetVisible, setBudgetVisible] = useState(false);
  const [selfItems, setSelfItems] = useState(false);
  const [currentItem, setCurrentItem] = useState({});
  const [qualityOperate, setQualityOperate] = useState(0);
  const [modifyManagerVisible, setModifyManagerVisible] = useState(false);
  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) => renderEditBtns(record),
    },
  ];

  const handleSearch = () => {
    const { projectName, projectCode, projectStatus } = form.getFieldsValue();
    let params = {};
    params.project_name = projectName;
    params.project_code = projectCode?.toUpperCase();
    params.project_status = projectStatus;
    params.currentPage = 1;

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

  const checkSelf = (e) => {
    let checked = e.target.checked;
    setCurrentItem({});
    setSelfItems(checked);
    dispatch({
      type: 'approval/queryApproval',
      payload: {
        filter_type: Number(checked),
        currentPage: 1,
      },
    });
  };

  const renderSearch = () => {
    return (
      <Form
        form={form}
        layout="inline"
        initialValues={{
          projectName: null,
          projectCode: null,
          projectStatus: null,
        }}
      >
        <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>
    );
  };

  const onOk = (values) => {
    if (values.id) {
      dispatch({
        type: 'approval/updateApproval',
        payload: values,
        callback: () => setAddVisible(false),
      });
    } else {
      dispatch({
        type: 'approval/createApproval',
        payload: values,
        callback: () => setAddVisible(false),
      });
    }
  };
  const onDelete = (item) => {
    Modal.confirm({
      title: '删除',
      content: '是否确认删除该项目',
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        dispatch({
          type: 'approval/deleteApproval',
          payload: item,
        });
      },
    });
  };
  const onSubmitAuth = (item) => {
    Modal.confirm({
      title: '提交审核',
      content: '是否确认提交审核',
      okText: '提审',
      cancelText: '取消',
      onOk() {
        dispatch({
          type: 'approval/submitAudit',
          payload: {
            id: item.id,
            flow_id: item.flow_id,
            node_id: item.node_id,
          },
        });
      },
    });
  };
  const queryList = (page) => {
    dispatch({
      type: 'approval/queryApproval',
      payload: {
        currentPage: page.current,
      },
    });
  };

  const renderEditBtns = (record) => {
    let dividerPush = (item, list) => {
      if (list.length === 0) list.push(item);
      else {
        list.push(<Divider type="vertical" />);
        list.push(item);
      }
    };
    let detailBtn = (
      <a
        onClick={() => {
          setCurrentItem(record);
          setDetailVisible(true);
        }}
      >
        项目详情
      </a>
    );
    let memberBtn = (
      <a
        onClick={() => {
          setCurrentItem(record);
          setMemberVisible(true);
        }}
      >
        成员管理
      </a>
    );
    let executionBtn = (
      <a
        onClick={() => {
          setCurrentItem(record);
          setExecutionVisible(true);
        }}
      >
        转执行
      </a>
    );
    let editBtn = (
      <>
        <a
          onClick={() => {
            setCurrentItem(record);
            setAddVisible(true);
          }}
        >
          编辑
        </a>
        <Divider type="vertical" />
        <a
          onClick={() => {
            onDelete(record);
          }}
        >
          删除
        </a>
        <Divider type="vertical" />
        <a
          onClick={() => {
            onSubmitAuth(record);
          }}
        >
          提交审核
        </a>
      </>
    );
    let statusBtn = (
      <>
        <a
          onClick={() => {
            setCurrentItem(record);
            dispatch({
              type: 'approval/queryBudget',
              payload: {
                project_id: record?.id,
              },
              callback: () => {
                setBudgetVisible(true);
              },
            });
          }}
        >
          设置人日预算
        </a>
        <Divider type="vertical" />
        <a
          onClick={() => {
            setCurrentItem(record);
            setQualityOperateVisible(true);
            setQualityOperate(0);
          }}
        >
          转质保
        </a>
        <Divider type="vertical" />
        <a
          onClick={() => {
            setCurrentItem(record);
            setQualityOperateVisible(true);
            setQualityOperate(1);
          }}
        >
          转运营
        </a>
      </>
    );
    let { audit_status, project_status, type_id } = record;
    //权限审核
    let canEdit = () => {
      if (user.IsSuper) return true;
      switch (audit_status) {
        case 0:
          return user.ID == record.author;
        case 1:
          return false;
        case 2:
          if (project_status == 0) return user.ID == record.author;
          if (project_status == 1) return user.ID == record.LeaderId;
          return false;
        case 3:
          switch (project_status) {
            case 0:
              return user.ID == record.author;
            case 1:
              return user.ID == record.LeaderId;
            case 2:
              return (
                user.ID == record.LeaderId || user.ID == record.opt_manager_id
              );
            case 3:
              return (
                user.ID == record.LeaderId || user.ID == record.wty_manager_id
              );
          }
          return false;
      }
    };
    let toReturn = [];
    dividerPush(detailBtn, toReturn);
    switch (audit_status) {
      //未提交
      case 0:
        canEdit() && dividerPush(editBtn, toReturn);
        break;
      //审核中
      case 1:
        break;
      //审核拒绝
      case 2:
        if (project_status == 0 && canEdit()) dividerPush(editBtn, toReturn);
        else if (project_status == 1 && canEdit()) {
          dividerPush(memberBtn, toReturn);
          dividerPush(statusBtn, toReturn);
        }
        break;
      //审核通过
      case 3:
        switch (project_status) {
          //售前
          case 0:
            if (canEdit()) {
              dividerPush(memberBtn, toReturn);
              dividerPush(executionBtn, toReturn);
            }
            break;
          //转执行
          case 1:
            if (canEdit()) {
              dividerPush(memberBtn, toReturn);
              dividerPush(statusBtn, toReturn);
            }
            break;
          //转运营
          case 2:
            canEdit() && dividerPush(memberBtn, toReturn);
            break;
          //转质保
          case 3:
            canEdit() && dividerPush(memberBtn, toReturn);
            break;
        }
        break;
    }
    let modifyManager = (
      <a
        onClick={() => {
          setCurrentItem(record);
          setModifyManagerVisible(true);
        }}
      >
        修改项目经理
      </a>
    );
    if (
      (project_status === 0 || project_status === 1) &&
      (user.Permission['func-01-point-pm-list-change'] || user.IsSuper)
    )
      dividerPush(modifyManager, toReturn);
    return toReturn;
  };

  useEffect(() => {
    dispatch({
      type: 'approval/queryFlow',
    });
    dispatch({
      type: 'approval/queryType',
    });
    dispatch({
      type: 'approval/queryIndustry',
    });
    dispatch({
      type: 'approval/queryApproval',
    });
    dispatch({
      type: 'approval/fetchDepV2',
    });
  }, []);

  return (
    <div>
      {renderSearch()}
      <div className={styles.btns}>
        <Button
          onClick={() => {
            setCurrentItem({});
            setAddVisible(true);
          }}
        >
          新增项目
        </Button>
        <Checkbox checked={selfItems} onChange={checkSelf}>
          只看自己
        </Checkbox>
      </div>
      <Table
        loading={loading}
        rowKey="id"
        dataSource={data.list}
        pagination={data.pagination}
        columns={columns}
        onChange={queryList}
      />
      <ApprovalModal
        currentUser={user}
        depUserTree={depUserTree}
        loading={loading}
        industryList={industryList}
        flowList={flowList}
        typeList={typeList}
        visible={addVisible}
        onOk={onOk}
        data={currentItem}
        total={data.pagination.total}
        onClose={() => setAddVisible(false)}
      />
      <DetailModal
        industryList={industryList}
        flowList={flowList}
        typeList={typeList}
        visible={detailVisible}
        data={currentItem}
        onClose={() => setDetailVisible(false)}
      />
      <ExecutionModal
        depUserTree={depUserTree}
        loading={loading}
        visible={executionVisible}
        currentItem={currentItem}
        onOk={() => setExecutionVisible(false)}
        onClose={() => setExecutionVisible(false)}
      />
      <MemberModal
        depUserTree={depUserTree}
        loading={loading}
        visible={memberVisible}
        onClose={() => setMemberVisible(false)}
        currentItem={currentItem}
        dataSource={member}
      />
      <QualityOperateModal
        depUserTree={depUserTree}
        loading={loading}
        visible={qualityOperateVisible}
        currentItem={currentItem}
        onOk={() => setQualityOperateVisible(false)}
        onClose={() => setQualityOperateVisible(false)}
        qualityOperate={qualityOperate}
      />
      <BudgetModal
        visible={budgetVisible}
        loading={loading}
        currentItem={currentItem}
        onCancel={() => setBudgetVisible(false)}
        onOk={() => setBudgetVisible(false)}
        budget={budget}
      />
      <ModifyManagerModal
        depUserTree={depUserTree}
        loading={loading}
        visible={modifyManagerVisible}
        onClose={() => setModifyManagerVisible(false)}
        currentItem={currentItem}
        dataSource={member}
        onOk={() => setModifyManagerVisible(false)}
      />
    </div>
  );
}

export default connect(({ approval, user, loading }) => ({
  data: approval.list,
  typeList: approval.typeList,
  flowList: approval.flowList,
  industryList: approval.industryList,
  loading: loading.models.approval,
  depUserTree: approval.depUserTree,
  member: approval.member,
  budget: approval.budget,
}))(List);
