import React, { useState, useRef, useEffect } from 'react';
import { Button, DatePicker, Input, Select, Space, Table, message } from 'antd';
import styles from './index.less';
import ContractModal, { Type } from './component/Modal';
import { PageContainer } from '@ant-design/pro-components';
import { useRequest, useModel } from '@umijs/max';
import { connect } from 'umi';
import {
  queryApproval,
  queryContract,
  queryContractCancel,
  queryGetContractList,
} from '../../services/contract';
import dayjs from 'dayjs';
import useModal from 'antd/es/modal/useModal';

const ConteactManager = (props) => {
  const { dispatch } = props;
  const [searchData, setSearchData] = useState({
    effect_on: '',
    project_name: '',
    status: '',
    page_size: 10,
    current: 0,
    name: '',
  });
  const { user } = useModel('userInfo');
  const [visible, setVisible] = useState(false);
  const [detail, setDetail] = useState({});
  const [data, setData] = useState([]);
  const [pagination, setPagination] = useState({ current: 0 });
  const typeRef = useRef();
  const parentIdRef = useRef(0);

  const showBtn = (record, type) => {
    let bool = false;
    switch (type) {
      case 'download':
        if (user?.Permission['menu-001-audit'] || record.created_by == user.ID)
          bool = true;
        break;
      case 'addOrCal':
        if (record.created_by == user.ID) bool = true;
        break;
    }
    return bool;
  };

  const columns = [
    {
      title: '合同编号',
      dataIndex: 'code',
      key: 'code',
      align: 'center',
      width: '12%',
    },
    {
      title: '合同生效时间',
      dataIndex: 'effect_on',
      key: 'effect_on',
      align: 'center',
    },
    {
      title: '合同名称',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
    },
    {
      title: '甲方',
      dataIndex: 'party_a',
      key: 'party_a',
      align: 'center',
    },
    {
      title: '丙方',
      dataIndex: 'party_c',
      key: 'party_c',
      align: 'center',
    },
    {
      title: '所属部门/子公司',
      dataIndex: 'dep_name',
      key: 'dep_name',
      align: 'center',
    },
    {
      title: '项目名称',
      dataIndex: 'project_name',
      key: 'project_name',
      align: 'center',
    },
    {
      title: '合同总价（万元）',
      dataIndex: 'amount',
      key: 'amount',
      align: 'center',
    },
    {
      title: '经办人',
      dataIndex: 'deal_by',
      key: 'deal_by',
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      render: (status) => {
        let str = '';
        switch (status) {
          case 1:
            str = '待审核';
            break;
          case 2:
            str = '审核拒绝';
            break;
          case 3:
            str = '已存档';
            break;
          case 4:
            str = '作废待审核';
            break;
          case 5:
            str = '作废拒绝';
            break;
          case 6:
            str = '已作废';
            break;
        }
        return <div>{str}</div>;
      },
    },
    {
      title: '操作',
      width: '210px',
      align: 'center',
      render: (record) => {
        return (
          <Space>
            <a
              onClick={() => {
                typeRef.current = Type.detail;
                parentIdRef.current = 0;
                setDetail(record);
                setVisible(true);
              }}
            >
              详情
            </a>
            <a onClick={handlePreView}>预览</a>
            {showBtn(record, 'download') && <a onClick={handleUpload}>下载</a>}
            {showBtn(record, 'addOrCal') && !record.parent_id && (
              <a
                onClick={() => {
                  typeRef.current = Type.add;
                  parentIdRef.current = record.id;
                  setDetail({});
                  setVisible(true);
                }}
              >
                增补
              </a>
            )}
            <a
              onClick={() => {
                typeRef.current = Type.cancel;
                setDetail(record);
                setVisible(true);
              }}
            >
              作废
            </a>
          </Space>
        );
      },
    },
  ];

  useEffect(() => {
    dispatch({
      type: 'user/fetch',
    });
  }, []);

  //请求列表
  const { run, loading } = useRequest((data) => queryGetContractList(data), {
    defaultParams: [searchData],
    onSuccess: (data) => {
      let resultData = data?.list?.map((item) => {
        return item.sub_num > 0 ? { ...item, children: [] } : item;
      });

      setData(resultData);
      setPagination(data?.pagination);
      // setData({ list: resultData, pagination: data?.pagination });
      console.log(data);
    },
  });
  //编辑新增接口
  const { run: editRun } = useRequest((data) => queryContract(data), {
    manual: true,
    onSuccess: () => {
      message.success('添加成功');
      setVisible(false);
      run(searchData);
    },
    onError: () => {
      message.success('添加失败');
    },
  });

  //作废发起
  const { run: calRun } = useRequest((data) => queryContractCancel(data), {
    manual: true,
    onSuccess: () => {
      message.success('发起作废成功');
      setVisible(false);
      run(searchData);
    },
    onError: () => {
      message.success('发起作废失败');
    },
  });

  //请求项目列表
  const { data: projectData } = useRequest(queryApproval, {
    defaultParams: [{ pageSize: 99999 }],
  });

  const handlePreView = () => {
    // originFileObj 是读取的文件对象，如上传组件读取到的
    // const fileURL = URL.createObjectURL(originFileObj);
    // window.open(fileURL);
  };

  const handleUpload = () => {};
  const handleSearch = () => {
    run(searchData);
  };
  const handleExport = () => {};

  const handleQueryChildren = async (req) => {
    const res = await queryGetContractList(req);
    if (res?.data?.list) {
      let resultData = [...data];
      let idx = data.findIndex((item) => item.id == req.is_parent);
      if (idx > -1) {
        resultData[idx].children = res?.data?.list;
        setData(resultData);
        setPagination(res.data?.pagination);
        // setData({ list: resultData, pagination: res.data?.pagination });
      }
    }
  };

  const handleOk = (data) => {
    if (typeRef.current == Type.add) {
      editRun(data);
    } else if (typeRef.current == Type.cancel) {
      calRun(data);
    }
  };
  const onPageChange = (page) => {
    run({ ...searchData, current: page });
  };
  return (
    <PageContainer>
      <div className={styles.searchContent}>
        <div className={styles.itemFlex}>
          <div>合同生效日期：</div>
          <DatePicker
            onChange={(e) => {
              setSearchData({
                ...searchData,
                effect_on: e ? dayjs(e).format('YYYY-MM-DD') : null,
              });
            }}
          />
        </div>
        <div className={styles.itemFlex}>
          <div>项目名称：</div>
          <Select
            style={{ width: 200 }}
            placeholder="请选择"
            onChange={(e) => {
              setSearchData({
                ...searchData,
                project_name: e,
              });
            }}
            options={projectData?.list?.map((item) => {
              return {
                value: item.project_name,
                label: item.project_name,
              };
            })}
          />
        </div>
        <div className={styles.itemFlex}>
          <div>状态：</div>
          <Select
            style={{ width: 150 }}
            placeholder="请选择"
            allowClear
            onChange={(e) => {
              setSearchData({
                ...searchData,
                status: e,
              });
            }}
            options={[
              { value: 3, label: '已归档' },
              { value: 1, label: '归档审核中' },
              { value: 4, label: '作废审核中' },
              { value: 6, label: '已作废' },
              { value: 2, label: '归档拒绝' },
              { value: 5, label: '作废拒绝' },
            ]}
          />
        </div>
        <Input
          className={styles.inputSty}
          placeholder="请输入合同名称/编号"
          allowClear
          onChange={(e) => {
            setSearchData({
              ...searchData,
              name: e.target.value,
            });
          }}
        />
        <Button
          type="primary"
          className={styles.searchBtnSty}
          onClick={handleSearch}
        >
          查询
        </Button>
        <Button
          type="primary"
          onClick={() => {
            typeRef.current = Type.add;
            setDetail({});
            setVisible(true);
          }}
        >
          新增
        </Button>
        <Button
          type="primary"
          className={styles.exportBtnSty}
          onClick={handleExport}
        >
          导出
        </Button>
      </div>
      <Table
        rowKey="code"
        loading={loading}
        columns={columns}
        dataSource={data}
        indentSize={70}
        onExpand={(expanded, record) => {
          console.log(expanded, record);
          if (expanded) handleQueryChildren({ is_parent: record.id });
        }}
        pagination={{ ...pagination, onChange: onPageChange }}
      />
      <ContractModal
        detail={detail}
        type={typeRef.current}
        parent_id={parentIdRef.current}
        projectList={projectData?.list}
        visible={visible}
        handleOk={handleOk}
        handleCancel={() => setVisible(false)}
      />
    </PageContainer>
  );
};
export default connect(({ user, loading }) => ({
  userList: user.list,
}))(ConteactManager);
