import {BarsOutlined, UploadOutlined} from "@ant-design/icons"
import {Button, Card, Checkbox, Col, Collapse, Form, Input, message, Modal, Row, Spin, Upload} from "antd"
import React, {useEffect, useRef, useState} from "react"
import style from './style.less'
import {GetfileUsablePackage, GetfileMsg, creatfile, creatNotice} from "../service";
import Weboffice from "@/pages/webOffice/weboffice";

import {deleteFileObjId, getFileBidList, SnowflakeID} from "@/services/untilService";

interface BiddingDocumentProps {
  modalVisible: boolean;
  titleName: string;
  onCancel: () => void;
  type: string;
  tpId: string;
  pkId: string;
  SX: () => void;
}

const layout = {
  labelCol: {span: 7},
  wrapperCol: {span: 10},
};
const BiddingDocument: React.FC<BiddingDocumentProps> = (props) => {
  const {Panel} = Collapse;
  const {titleName, modalVisible, onCancel, type, tpId, pkId, SX} = props;
  const [TpPackageId, setTpPackageId] = useState<any[]>([]); //标包信息
  const [spinning, setSping] = useState<boolean>();//加载遮罩
  const [editInformation, setEditInformation] = useState<boolean>(false);//是否可编
  const [form] = Form.useForm();
  const [docFileCode, setDocFileCode] = useState<string>("");//文档id
  const [docBtnName, setDocBtnName] = useState<any>("");//文档按钮文字
  const [docReadOnly, setDocReadOnly] = useState<string>("false");//是否可编辑
  const [docSaveBtn, setDocSaveBtn] = useState<string>("compact");//保存按钮是否展示
  const [UploadList, setUploadList] = useState<any>();		//存upload列表
  const [UploadID, setUploadID] = useState<any>(); //upload 业务id

  /*weboffice 相关*/
  const WebofficeRef = useRef<Weboffice>(null);
  const onRef = (ref) => {
    /* this.child= ref;*/
  }


  useEffect(() => {
    SnowflakeID().then(res => {
      Int();
    });
    form.resetFields();//清除form中数据
  }, [type, pkId]);
  useEffect(() => {
    UploadMethod();
  }, [UploadID]);
  const Int = () => {
    setSping(true);
    if (type == "cease") {
      return;
    } else if (type == "new") {//==========================================================新建
      GetfileUsablePackage(tpId).then(res => {
        if (res != null && res.message == "success") {
          let thisData = [];
          if (res.data.length == 0) {
            message.warn("没有可关联的标包！")
            onCancel();
          }
          for (const item of res.data) {
            thisData.push({"label": item.bsName, "value": item.bsId})
          }
          SnowflakeID().then(res => {
            setUploadID(res.id);
          });
          setTpPackageId(thisData);
          setDocReadOnly("false")
          setDocSaveBtn("compact")
          setDocBtnName("新建")
        } else {
          message.error('程序出错，请您稍后再试:'+res.message);
          onCancel();
        }
        setSping(false);
        setEditInformation(false);//可编辑
      });

    } else if (type == "edit") {//=========================================================修改
      let thisData1:any [];
      GetfileUsablePackage(tpId).then(res => {
        if (res != null && res.message == "success") {
          let thisData2 = [];
          for (const item of res.data) {
            thisData2.push({"label": item.bsName, "value": item.bsId})
          }
          thisData1=thisData2;
        } else {
          message.error('程序出错，请您稍后再试:'+res.message);
          onCancel();
        }
        GetfileMsg(pkId).then(res => {
          if (res != null && res.message == "success") {
            const data = res.data;
            let defPak=[];
            for (const item of data.sections) {
              thisData1.push({"label": item.bsName, "value": item.bsId})
              defPak.push(item.bsId);
            }
            setTpPackageId(thisData1);
            form.setFieldsValue({
                "documentName": data.documentName,
                "documentSetId": data.documentSetId,
                "sectionIds":defPak,
              },
            )

            setUploadID(data.documentSetId);
            setSping(false);
            setEditInformation(false);//可编辑
            setDocFileCode(data.contentFileId);
            setDocReadOnly("false")
            setDocSaveBtn("compact")
            setDocBtnName("编辑")
          } else {
            message.error('程序出错，请您稍后再试:'+res.message);
            onCancel();
          }
        });
      });

    } else if (type == "read") {//=========================================================查看
      GetfileMsg(pkId).then(res => {
        if (res != null && res.message == "success") {
          const data = res.data;
          let thisData1 = [];
          let defPak=[];
          for (const item of data.sections) {
            thisData1.push({"label": item.bsName, "value": item.bsId})
            defPak.push(item.bsId);
          }
          setTpPackageId(thisData1);
          form.setFieldsValue({
              "documentName": data.documentName,
              "documentSetId": data.documentSetId,
              "sectionIds":defPak,
            },
          )


          setSping(false);
          setEditInformation(true)
          setDocFileCode(data.contentFileId);
          setUploadID(data.documentSetId);
          setDocReadOnly("true")
          setDocSaveBtn("none")
          setDocBtnName("查看")
        } else {
          message.error('程序出错，请您稍后再试:'+res.message);
          onCancel();
        }
      });
    }
    /*upload*/

  }


  const onFinish = async (values: any) => {
    form.validateFields().then(res => {
      if (type == "new") {//==========================================================新建
        if (WebofficeRef.current!.uninitialized == true) {//
          message.warn("您未编辑office文件！");
          return;
        } else {
          if (WebofficeRef.current!.uploadDOCType != "success") {
            message.warn("您未保存office文件！");
            return;
          }
        }
      } else if (type == "edit") {//=========================================================修改
        if (WebofficeRef.current!.uninitialized == false) {//
          if (WebofficeRef.current!.uploadDOCType != "success") {
            message.warn("您未保存office文件！");
            return;
          }
        }
      }


      const packageMsg = [];
      for (const item of TpPackageId) {//包数据
        for (const item1 of form.getFieldValue("sectionIds"))
          if (item.value == item1)
            packageMsg.push({"bsId": item.value, "bsName": item.label})
      }

      const fromData = {
        "tpId": tpId,
        "documentName": form.getFieldValue("documentName"),
        "documentSetId": UploadID,
        "sections": packageMsg,
        "contentFileId": WebofficeRef.current!.DocfileCode,
        "id": pkId
      }
      setSping(true);
       creatfile(type, fromData).then(res => {
        if (res != null && res.message == "success") {
          message.success("成功");
          setSping(true);
          onCancel();
          SX();
        } else {
          message.error("保存失败:"+res.message);
          setSping(true);
        }
      });
    }).catch(res => {
      message.warn("您有未填写的选项！")
    })
  };
  const renderFooter = () => {
    if (type == "read") {
      return (
        <>
          <Button onClick={onCancel}>确认</Button>
        </>
      );
    } else {
      return (
        <>
          <Button onClick={onFinish}>确认</Button>
          <Button onClick={onCancel}>取消</Button>
        </>
      );
    }
  }


  const UploadMethod = () => {
    getFileBidList(UploadID).then(res => {
      setUploadList(res)
    })
  }
  const UploadOnchange = async (file:any) => {
    let fileMsg = file.file;
    if (fileMsg.status === 'removed') {
      await deleteFileObjId(fileMsg.uid)
      setUploadList(file.fileList)
    }
    if (fileMsg.status === 'done') {
      message.success("上传成功");
      await UploadMethod();
    } else if (fileMsg.status === 'error') {
      message.error("上传失败");
    }
  }

  // @ts-ignore
  return (
    <Modal
      mask={true}
      destroyOnClose
      title={titleName}
      visible={modalVisible}
      onCancel={() => onCancel()}
      className="返回"
      width={1000}
      bodyStyle={{padding: '32px 40px 48px', height: "600px", overflowY: 'auto'}}
      footer={renderFooter()}
    >
      <Spin spinning={spinning}>
        <Card>
          <Form
            {...layout}
            name="basic"
            form={form}
          >
            <Form.Item
              label="文件名称"
              name="documentName"
              rules={[
                {
                  required: true,
                  message: '当前项不可为空',
                },
              ]}
            >
              <Input readOnly={editInformation}/>
            </Form.Item>
            <Form.Item
              label="关联标段"
              name="sectionIds"
              rules={[
                {
                  required: true,
                  message: '当前项不可为空',
                },
              ]}
            >
              <Checkbox.Group

                options={TpPackageId}
                style={{width: '100%'}}
                disabled={editInformation}
              >
              </Checkbox.Group>
            </Form.Item>
            <Form.Item
              label="招标文件附件"
              name="documentSetId"
            >
              <div className={style.bidding}>
                <div className="uploadTotal">
                  <Upload
                    {...UploadMethod}
                    action={'/api/core-service-ebtp-updownload/v1/attachment/upload'}
                    data={{"businessId": UploadID}}
                    fileList={UploadList}
                    onChange={UploadOnchange}
                  >
                    <Button type="primary" disabled={editInformation} className="upload"><UploadOutlined/>上传</Button>
                  </Upload>
                  <p className="uploadLabel">最大能上传100M文件！</p>
                </div>
              </div>
            </Form.Item>
          </Form>
          <Collapse defaultActiveKey={['1']} ghost expandIcon={() => <BarsOutlined/>}>
            <Panel header="招标文件内容" key="1">
              <Card style={{textAlign: "center"}}>
                <div>
                  {docBtnName != "" ?
                    <Weboffice memberBtnName={docBtnName} readonly={docReadOnly} btnStyle={docSaveBtn} btnName={"保存"}
                               DocfileCode={docFileCode} ref={WebofficeRef} onRef={onRef}/>
                    : null
                  }
                </div>
              </Card>
            </Panel>
          </Collapse>
        </Card>
      </Spin>
    </Modal>

  )
}
export default BiddingDocument
