import { btnAuthority } from "@/utils/authority";
import ProTable, { ProColumns } from "@ant-design/pro-table";
import { Button, Card, Col, Input, message, Modal, Row, Spin, } from "antd";
import React, { useEffect, useRef, useState } from "react";
import '@/assets/xsy_style.less';
import { getSupplierList, getSupplierUser } from "@/utils/SupplierList/service";
import { getURLInformation } from "@/utils/CommonUtils";
import { addGys, addMan, deleteGys, getSimpleList } from "./simpleUploadServis";
import ExtendUpload from "@/utils/ExtendUpload";
import { SnowflakeID } from "@/services/untilService";

const SimpleUpload: React.FC<{}> = (props) => {
  //=======================================================================state
  const [spin, spinSet] = useState(false);
  const [data, dataSet] = useState([]);
  const roomId = getURLInformation('roomId');
  const bsId = getURLInformation('bsId');
  const tpId = getURLInformation('tpId');
  const dis = getURLInformation('dis') == '3';

  //添加供应商
  const [addVis, addVisSet] = useState(false);
  const [serchVal, serchValSet] = useState('');
  const [gysData, gysDataSet] = useState([]);
  const [spinGys, spinGysSet] = useState(false);
  const serchGysRef = useRef<any>(null)
  //选择联系人
  const [manVis, manVisSet] = useState(false);
  const [companyId, companyIdSet] = useState(false);
  const [recordId, recordIdSet] = useState('');
  const [spinMan, spinManSet] = useState(false);
  //上传文件
  const [fileVis, fileVisSet] = useState(false);
  const [UploadID, setUploadID] = useState<any>(); //upload 业务id
  const [spinUp, spinUpSet] = useState(false);
  //查询分页数据
  const [pageData, pageDataSet] = useState<any>({
    total: 0,
    pageNum: 1,
    pageSize: 10
  });
  const columns: ProColumns<any>[] = [
    {
      title: '序号', valueType: 'index', width: 60
    },
    {
      title: '机构编号', dataIndex: 'companyId',
    },
    {
      title: '供应商', dataIndex: 'companyName',
    },
    {
      title: '联系人', dataIndex: 'bidUserName',
    },
    {
      title: '联系人账号', dataIndex: 'bidUserId',
    },
    {
      title: '应答文件上传状态', dataIndex: 'decryptStatus',
      render: (_, record,) => {
        if (record.singleSourceAnswerFile != '' && record.singleSourceAnswerFile != null) {
          return '已上传'
        } else { return '未上传' }
      }
    },
    {
      title: '操作', dataIndex: 'option', valueType: 'option',
      render: (_, record, index) => {
        return (
          <>
            <Button type='text' hidden={btnAuthority(["ebtp-agency-project-manager", "ebtp-purchase"]) || dis} onClick={() => { manVisSet(true); companyIdSet(record.companyId); recordIdSet(record.id) }}>选择/变更联系人</Button>
            <Button type='text' hidden={btnAuthority(["ebtp-agency-project-manager", "ebtp-purchase"])} style={{ marginLeft: dis ? 0 : 10 }} onClick={async () => {
              recordIdSet(record.id);
              if (record.singleSourceAnswerFile) {
                setUploadID(record.singleSourceAnswerFile);
              } else {
                await SnowflakeID().then(res => {
                  setUploadID(res.id);
                });
              }
              fileVisSet(true);
            }}>{dis ? '查看应答文件' : '上传应答文件'}</Button>
            <Button type='text' hidden={btnAuthority(["ebtp-agency-project-manager", "ebtp-purchase"]) || dis} style={{ marginLeft: 10 }} onClick={async () => {
              spinSet(true);
              await deleteGys(record.id).then((res) => {
                if (res.success) {
                  message.success('删除成功！');
                }
              })
              serchList();
            }}>删除</Button>
          </>
        )
      }
    },
  ];
  const columnsGys: ProColumns<{}>[] = [
    {
      title: '供应商名称',
      dataIndex: 'partnerName',
      key: 'partnerName',
      align: 'left',
    },
    {
      title: '供应商编号',
      dataIndex: 'organizationCode',
      key: 'organizationCode',
      hideInSearch: true,//列表中显示，查询条件中不显示
      align: 'left',
    },
    {
      title: '操作',
      dataIndex: 'status',
      key: "",
      hideInSearch: true,//列表中显示，查询条件中不显示
      align: 'left',
      render: (_: any, record: any) => (
        <Button hidden={btnAuthority(["ebtp-agency-project-manager", "ebtp-purchase"])} onClick={() => chooseGys(record)} type="text">选择</Button>
      )
    },
  ];
  const columnsMan: ProColumns<{}>[] = [
    {
      title: '联系人',
      dataIndex: 'empName',
      key: 'empName',
      align: 'left',
    },
    {
      title: '账号',
      dataIndex: 'userAccount',
      key: 'userAccount',
      search: false,
      align: 'left',
    },
    {
      title: '电话',
      dataIndex: 'mobile',
      key: 'mobile',
      search: false,
      align: 'left',
    },
    {
      title: '操作',
      dataIndex: 'status',
      align: 'left',
      search: false,
      render: (_: any, record: any) => (
        <Button onClick={async () => {
          spinManSet(true);
          await chooseSupplierUser({
            id: recordId,
            bidUserId: record.userAccount,
            bidUserName: record.empName,
          });
          spinManSet(false);
          manVisSet(false);
          serchList();
        }} type="text">选择</Button>
      )
    },
  ];
  //=======================================================================func
  useEffect(() => {
    serchList();
  }, []);
  useEffect(() => {
    addVis && serchGys();
  }, [pageData.pageNum]);

  //查询列表
  async function serchList() {
    spinSet(true);
    await getSimpleList(roomId).then((res) => {
      if (res.success) {
        dataSet(res.data)
      }
    })
    spinSet(false);
  }
  //查询供应商
  async function serchGys() {
    spinGysSet(true);
    await getSupplierList({ partnerName: serchVal, pageNum: pageData.pageNum }).then((res) => {
      if (res.success) {
        gysDataSet(res.data.records);
        pageDataSet({ ...pageData, total: res.data.total });
        if (res.data.records.length == 0) {
          message.info('无符合条件的供应商，请确认输入的供应商名称是否正确。')
        }
      }
    })
    spinGysSet(false);
  }
  //选择供应商
  async function chooseGys(record: any) {
    spinGysSet(true);
    const params = {
      companyId: record.partnerMdmCode,
      companyName: record.partnerName,
      assessRoomId: roomId,
      packageId: bsId,
      projectId: tpId,
    }
    await addGys(params).then((res) => {
      if (res.success) {
        message.success('选择供应商成功，请选择邀请账号。');
        addVisSet(false);
        serchList();
      }
    });
    addVisSet(false);
    spinGysSet(false);
  }
  /*选择供应商联系人*/
  const chooseSupplierUser = async (param: any) => {
    await addMan(param).then(res => {
      if (res.code == 200) {
        message.success("保存成功");
      }
    })
  }
  //=======================================================================dom
  function addModal() {
    return (
      <Modal
        visible={addVis}
        style={{ overflowX: 'hidden', position: 'relative', }}
        bodyStyle={{ maxHeight: "700px", overflowY: 'auto', overflowX: 'hidden' }}
        width={gysData.length != 0 ? 1000 : 500}
        centered
        destroyOnClose
        maskClosable={false}
        title="选择供应商"
        footer={gysData.length != 0 ? renderFooter() : null}
        onCancel={() => {
          addVisSet(false);
          pageDataSet({ total: 0, pageNum: 1, pageSize: 10 });
        }}
      >
        <Spin spinning={spinGys}>
          <Row justify={gysData.length != 0 ? 'end' : 'center'}>
            <Col flex='350px'>
              <Input ref={serchGysRef} value={serchVal} onChange={(e) => { serchValSet(e.target.value) }} onPressEnter={() => serchGys()} placeholder='请输入要查询的供应商名称' />
            </Col>
            <Col>
              <Button type='primary' style={{ marginLeft: '5px' }} hidden={btnAuthority(["ebtp-agency-project-manager", "ebtp-purchase"])} onClick={() => serchGys()}>
                查找
              </Button>
            </Col>
          </Row>
          {
            gysData.length != 0 &&
            <ProTable
              options={false}
              search={false}
              size="small"
              style={{ marginTop: '16px' }}
              columns={columnsGys}
              dataSource={gysData}
              pagination={{
                defaultPageSize: 10,
                total: pageData.total,
                showSizeChanger: false,
                onChange: (page, pageSize) => pageDataSet({ ...pageData, pageNum: page, pageSize: pageSize }),
                onShowSizeChange: (current, size) => pageDataSet({ ...pageData, pageNum: current, pageSize: size }),
              }}
            />
          }
        </Spin>
      </Modal>
    )
  }
  function renderFooter() {
    return (
      <>
        <Button type='primary' onClick={() => {
          addVisSet(false);
          manVisSet(false);
          fileVisSet(false);
          pageDataSet({ total: 0, pageNum: 1, pageSize: 10 });
        }}>关闭</Button>
      </>
    )
  }
  function renderFooterUp() {
    return (
      <>
        <Button type='primary' loading={spinUp} onClick={async () => {
          spinUpSet(true);
          await chooseSupplierUser({ id: recordId, singleSourceAnswerFile: UploadID });
          spinUpSet(false);
          fileVisSet(false);
          serchList();
        }}>保存</Button>
      </>
    )
  }
  //联系人modal
  function chooseMan() {
    return (
      <Modal
        visible={manVis}
        style={{ overflowX: 'hidden', position: 'relative', }}
        bodyStyle={{ maxHeight: "700px", overflowY: 'auto', overflowX: 'hidden' }}
        width={1000}
        centered
        destroyOnClose
        maskClosable={false}
        title="选择联系人"
        footer={renderFooter()}
        onCancel={() => {
          manVisSet(false);
          pageDataSet({ total: 0, pageNum: 1, pageSize: 10 });
        }}
      >
        <Spin spinning={spinMan}>
          <ProTable
            options={false}
            size="small"
            style={{ marginTop: '16px' }}
            columns={columnsMan}
            request={async (params) => {
              const msg = await getSupplierUser({
                ...params, partnerMdmCode: companyId, pageNum: params.current, pageSize: params.pageSize,
              });
              return {
                data: msg.data?.records, success: msg?.success, total: msg?.data.total,
              }
            }}
            pagination={{
              defaultPageSize: 10,
              showSizeChanger: false,
            }}
          />
        </Spin>
      </Modal>
    )
  }
  //上传文件
  function uploadFile() {
    return (
      <Modal
        visible={fileVis}
        style={{ overflowX: 'hidden', position: 'relative', }}
        bodyStyle={{ maxHeight: "700px", overflowY: 'auto', overflowX: 'hidden' }}
        width={500}
        centered
        destroyOnClose
        maskClosable={false}
        title="上传应答文件"
        footer={dis ? renderFooter() : renderFooterUp()}
        onCancel={() => fileVisSet(false)}
      >
        <Spin spinning={spinUp}>
          <Row align="middle">
            <Col span={4}>应答文件:</Col>
            <Col span={14}>
              <ExtendUpload
                uploadProps={{ name: "file", disabled: dis }}
                maxCount={1}
                bid={UploadID}
              />
            </Col>
          </Row>
          <Row align="bottom" style={{ marginTop: 10 }}>
            <Col offset={4}>上传成功后，请点击保存按钮 (单个附件最大30MB)</Col>
          </Row>
        </Spin>
      </Modal>
    )
  }
  return (
    <Card>
      <Spin spinning={spin}>
        <div className='xsy-headerDiv'>
          <h3 className="first-title floatLeft">添加供应商及上传应答文件</h3>
          <div className='xsy-rightDiv'>
            <Button
              type='primary'
              disabled={data.length != 0 || spin}
              hidden={btnAuthority(["ebtp-agency-project-manager", "ebtp-purchase"])}
              style={{ marginLeft: '10px' }}
              onClick={() => {
                addVisSet(true);
                setTimeout(() => {
                  serchGysRef.current!.focus({ cursor: serchVal == '' ? 'start' : 'all' });
                }, 100);
              }}
            >添加供应商</Button>
            <Button style={{ marginLeft: '10px' }} onClick={() => { history.back() }}>返回</Button>
          </div>
        </div>

        <ProTable
          options={false}
          search={false}
          size="small"
          columns={columns}
          dataSource={data}
          pagination={false}
        />
      </Spin>
      {addModal()}
      {chooseMan()}
      {uploadFile()}
    </Card>
  )
}
export default SimpleUpload;