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,
  queryContractCancelCheck,
  queryContractDownload,
  queryGetContractList,
} from '../../services/contract';
import dayjs from 'dayjs';
import FileViewerModal from '@/components/FileViewerNew';
import { getToken } from '@/utils/utils';
import PageContent from '@/components/PageContent';
import EllipsisText from './component/EllipsisText';

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

  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: 160,
    },
    {
      title: '合同签订时间',
      dataIndex: 'effect_on',
      key: 'effect_on',
      align: 'center',
      width: 120,
    },
    {
      title: '合同名称',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
    },
    {
      title: '甲方',
      dataIndex: 'party_a',
      key: 'party_a',
      align: 'center',
      render: (text) => <EllipsisText text={text} width={120} />,
    },
    {
      title: '乙方',
      dataIndex: 'party_b',
      key: 'party_b',
      align: 'center',
      render: (text) => <EllipsisText text={text} width={120} />,
    },
    {
      title: '丙方',
      dataIndex: 'party_c',
      key: 'party_c',
      align: 'center',
      render: (text) => {
        let str = text;
        try {
          str = JSON.parse(text).join('、');
        } catch (error) {}
        return <EllipsisText text={str} width={120} />;
      },
    },
    {
      title: '所属部门/子公司',
      dataIndex: 'dep_name',
      key: 'dep_name',
      align: 'center',
      width: 160,
    },
    {
      title: '项目名称',
      dataIndex: 'project_name',
      key: 'project_name',
      align: 'center',
      width: 120,
    },
    {
      title: '合同总价（万元）',
      dataIndex: 'amount',
      key: 'amount',
      align: 'center',
      width: 160,
    },
    {
      title: '经办人',
      dataIndex: 'deal_by',
      key: 'deal_by',
      align: 'center',
      width: 80,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      width: 100,
      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(record)}>预览</a>
            {showBtn(record, 'download') && (
              <a onClick={() => handleUpload(record)}>下载</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);
    },
  });
  //编辑新增接口
  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 { run: calCheckRun } = useRequest(
    (data) => queryContractCancelCheck(data),
    {
      manual: true,
      onSuccess: () => {
        message.success('审核成功');
        setVisible(false);
        run(searchData);
      },
      onError: () => {
        message.success('审核失败');
      },
    },
  );

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

  const handlePreView = (record) => {
    if (!record.attach) return;
    const attach = JSON.parse(record.attach);
    setFileViewerData(attach);
    setFileViewerVisible(true);
  };

  const handleUpload = (record) => {
    const token = getToken();
    window.downloadFile(
      `/api/contract/v1/contract/download?id=${record.id}&JWT-TOKEN=${token}`,
      record.name,
      false,
    );
  };
  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);
    } else {
      calCheckRun(data);
    }
  };
  const onPageChange = (page) => {
    run({ ...searchData, current: page });
  };
  return (
    <PageContent>
      <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
          style={{ width: 150 }}
          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)}
      />
      <FileViewerModal
        data={fileViewerData}
        visible={fileViewerVisible}
        downloadFile={() => {}}
        onCancel={() => {
          setFileViewerVisible(false);
        }}
      />
    </PageContent>
  );
};
export default connect(({ user, loading }) => ({
  userList: user.list,
}))(ConteactManager);
