import { BarsOutlined, UploadOutlined } from "@ant-design/icons"
import { Button, Card, Checkbox, Col, Collapse, DatePicker, 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";
import ExtendUpload from "@/utils/ExtendUpload";
import { UploadProps } from "antd/lib/upload/interface";
import { getProMethod } from "@/utils/session";
import WebOffice0609, { WebOfficeRefProps } from "@/pages/webOffice/weboffice0609";
import moment from "moment";
import { AnnouncementGetMsg1, AnnouncementGetMsg2, AnnouncementGetMsg3, AnnouncementGetMsg4 } from "@/utils/AboutAnnouncementHelp";
import { trim } from "@/utils/CommonUtils";

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<boolean>(false);//是否可编辑
  const [docSaveBtn, setDocSaveBtn] = useState<string>("compact");//保存按钮是否展示
  const [UploadList, setUploadList] = useState<any>();		//存upload列表
  const [UploadID, setUploadID] = useState<any>("empty"); //upload 业务id

  const UploadProps: UploadProps = {
    name: "file",
    disabled: editInformation
  }

  let pktittle = "";
  let name1 = "招标";
  let proDict = getProMethod();
  if (proDict == "procurement_mode_1" || proDict == "procurement_mode_2") {
    pktittle = "标段";
    name1 = "招标";
  } else if (proDict == "procurement_mode_3") {
    pktittle = "采购包"
    name1 = "采购";
  } else if (proDict == "procurement_mode_5" || proDict == "procurement_mode_6" || proDict == "procurement_mode_9") {
    pktittle = "采购包"
    name1 = "采购";

  } else if (proDict == "procurement_mode_4") {
    pktittle = "包件"
    name1 = "招募";

  }



  /*weboffice 相关*/
  const ref = useRef<WebOfficeRefProps>();
  // const WebofficeRef = useRef<Weboffice>(null);
  // const onRef = (ref) => {
  //   /* this.child= ref;*/
  // }
  //DatePicker
  function disabledDate(current: any) {//日期选择
    // 不能选今天之前
    return current && current < moment().startOf('day');
  }
  const ReplyEndTimechange1 = (data?: any) => {
    if (data != undefined) {
      form.setFieldsValue({
        "openingTime": moment(data, 'yyyy-MM-DD HH:mm:ss'),
      });
    }
  };

  useEffect(() => {
    SnowflakeID().then(res => {
      Int();
    });
    form.resetFields();//清除form中数据
  }, [type, pkId]);
  const Int = () => {

    setSping(true);
    if (type == "new") {//==========================================================新建
      GetfileUsablePackage(tpId).then(res => {
        if (res.code == 200) {
          let thisData = [];
          for (const item of res.data) {
            thisData.push({ "label": item.bsName, "value": item.bsId })
          }
          setUploadID("")
          setTpPackageId(thisData);
          setDocReadOnly(false)
          setDocSaveBtn("compact")
          setSping(false);
          setEditInformation(false);//可编辑
          setDocBtnName("新建")
        }
      });

    } else if (type == "edit") {//=========================================================修改
      GetfileUsablePackage(tpId, pkId).then(res => {
        if (res.code == 200) {
          let thisData2 = [];
          for (const item of res.data) {
            thisData2.push({ "label": item.bsName, "value": item.bsId })
          }
          setTpPackageId(thisData2);


        }
        GetfileMsg(pkId).then(res => {
          if (res.code == 200) {
            const data = res.data;
            let defPak = [];
            for (const item of data.sections) {
              defPak.push(item.bsId);
            }
            form.setFieldsValue({
              "documentName": data.documentName,
              "documentSetId": data.documentSetId,
              "sectionIds": defPak,
            });
            if (proDict == "procurement_mode_9") {
              form.setFieldsValue({
                "docStartTime": moment(data.docStartTime, 'yyyy-MM-DD HH:mm:ss'),
                "replyEndTime": moment(data.replyEndTime, 'yyyy-MM-DD HH:mm:ss'),
                "openingTime": moment(data.openingTime, 'yyyy-MM-DD HH:mm:ss'),
                "docEndTime": moment(data.docEndTime, 'yyyy-MM-DD HH:mm:ss'),
              })
            }
            setUploadID(data.documentSetId);
            setSping(false);
            setEditInformation(false);//可编辑
            setDocFileCode(data.contentFileId);
            setDocReadOnly(false)
            setDocSaveBtn("compact")
            setDocBtnName("编辑")
          }
        });
      });

    } else if (type == "read") {//=========================================================查看
      GetfileMsg(pkId).then(res => {
        if (res.code == 200) {
          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,
          })
          if (proDict == "procurement_mode_9") {
            form.setFieldsValue({
              "docStartTime": moment(data.docStartTime, 'yyyy-MM-DD HH:mm:ss'),
              "replyEndTime": moment(data.replyEndTime, 'yyyy-MM-DD HH:mm:ss'),
              "openingTime": moment(data.openingTime, 'yyyy-MM-DD HH:mm:ss'),
              "docEndTime": moment(data.docEndTime, 'yyyy-MM-DD HH:mm:ss'),
            })
          }
          setSping(false);
          setEditInformation(true)
          setDocFileCode(data.contentFileId);
          setUploadID(data.documentSetId);
          setDocReadOnly(true)
          setDocSaveBtn("none")
          setDocBtnName("查看")
        }
      });
    }
    /*upload*/

  }


  const onFinish = async (values: any) => {
    form.validateFields().then(res => {
      if (type == "new") {//==========================================================新建
        if (ref.current?.DocFileCode == '') {
          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 })
      }

      let fromData = {
        "tpId": tpId,
        "documentName": trim(form.getFieldValue("documentName")),
        "documentSetId": form.getFieldValue("documentSetId"),
        "sections": packageMsg,
        "contentFileId": ref.current?.DocFileCode,
        "id": pkId
      };
      if (proDict == "procurement_mode_9") {
        fromData["docStartTime"] = form.getFieldValue("docStartTime").format("yyyy-MM-DD HH:mm:ss").toString();
        fromData["replyEndTime"] = form.getFieldValue("replyEndTime").format("yyyy-MM-DD HH:mm:ss").toString();
        fromData["openingTime"] = form.getFieldValue("openingTime").format("yyyy-MM-DD HH:mm:ss").toString();
        fromData["docEndTime"] = form.getFieldValue("docEndTime").format("yyyy-MM-DD HH:mm:ss").toString();
      }
      setSping(true);
      creatfile(type, fromData).then(res => {
        if (res.code == 200) {
          message.success("成功");
          onCancel();
          SX();
        }
      }).finally(() => setSping(false));
    }).catch(res => {
      message.warn("您有未填写的选项！")
    })
  };
  const renderFooter = () => {
    if (type == "read") {
      return (
        <>
          <Button onClick={onCancel}>关闭</Button>
        </>
      );
    } else {
      return (
        <>
          <Button type="primary" loading={spinning} onClick={onFinish}>确认</Button>
          <Button onClick={onCancel}>取消</Button>
        </>
      );
    }
  }


  // @ts-ignore
  return (
    <Modal
      mask={true}
      destroyOnClose
      title={titleName}
      visible={modalVisible}
      onCancel={() => onCancel()}
      className="返回"
      width={"60%"}
      /*style={{top: "2%", height: "96%", overflowY: "auto"}}
      bodyStyle={{paddingTop: "16px"}}*/
      centered
      footer={renderFooter()}
    >
      <Spin spinning={spinning}>
        <Form
          {...layout}
          name="basic"
          form={form}
        >
          <Form.Item
            label="文件名称"
            name="documentName"
            rules={[
              {
                required: true,
                message: '当前项不可为空',
              },
            ]}
          >
            <Input maxLength={200} readOnly={editInformation} />
          </Form.Item>

          {//单一来源简化流程
            proDict == "procurement_mode_9" &&
            <>
              <Form.Item
                label={name1 + "文件获取开始时间"}
                name="docStartTime"
                rules={[
                  {
                    required: true,
                    message: '当前项不可为空',
                  },
                ]}
              >
                <DatePicker showNow={false} disabled={editInformation} showTime={{ defaultValue: moment().startOf('minute') }}
                  style={{ width: "100%" }} disabledDate={disabledDate} format={"yyyy-MM-DD HH:mm"} />
              </Form.Item>
              <Form.Item
                label={name1 + "文件获取截止时间"}
                name="docEndTime"
                rules={[
                  {
                    required: true,
                    message: '当前项不可为空',
                  },
                ]}
              >
                <DatePicker showNow={false} disabled={editInformation} showTime={{ defaultValue: moment().startOf('minute') }}
                  style={{ width: "100%" }} disabledDate={disabledDate} format={"yyyy-MM-DD HH:mm"} />
              </Form.Item>
              <Form.Item
                label={"应答截止时间"}
                name="replyEndTime"
                rules={[
                  {
                    required: true,
                    message: '当前项不可为空',
                  },
                ]}
              >
                <DatePicker showNow={false} disabled={editInformation} showTime={{ defaultValue: moment().startOf('minute') }}
                  style={{ width: "100%" }} disabledDate={disabledDate} format={"yyyy-MM-DD HH:mm"} onChange={(data: any) => ReplyEndTimechange1(data)} />
              </Form.Item>
              <Form.Item
                label={"评审开始时间"}
                name="openingTime"
                rules={[
                  {
                    required: true,
                    message: '当前项不可为空',
                  },
                ]}
              >
                <DatePicker showNow={false} disabled={editInformation} showTime={{ defaultValue: moment().startOf('minute') }}
                  style={{ width: "100%" }} disabledDate={disabledDate} format={"yyyy-MM-DD HH:mm"} />
              </Form.Item>
              <Form.Item
                label="采购文件获取方式"
                name="documentGetWay"
              >
                线下获取
              </Form.Item>
              <Form.Item
                label="应答文件递交方式"
                name="documentSubmitWay"
              >
                在线递交
              </Form.Item>
            </>
          }
          <Form.Item
            label={"关联" + pktittle}
            name="sectionIds"
            rules={[
              {
                required: true,
                message: '当前项不可为空',
              },
            ]}
          >
            <Checkbox.Group

              options={TpPackageId}
              style={{ width: '100%' }}
              disabled={editInformation}
            >
            </Checkbox.Group>
          </Form.Item>
          <Form.Item
            label="附件"
            name="documentSetId"
            extra="单个附件最大30MB"
          >
            {UploadID != "empty" ? <ExtendUpload uploadProps={UploadProps} bid={UploadID} /> : null}
          </Form.Item>
        </Form>
        <h3 className="first-title">{name1}文件内容</h3>
        <Card style={{ textAlign: "center" }}>
          <div>
            {/* {docBtnName != "" ? (
              <Weboffice key={""} memberBtnName={docBtnName} readonly={docReadOnly} btnStyle={docSaveBtn}
                btnName={"保存"}
                DocfileCode={docFileCode} saveHTML={"0"} savePDF={"0"} ref={WebofficeRef}
                onRef={onRef} />) : null} */}
            {docBtnName != "" ? (
              <WebOffice0609
                readOnly={docReadOnly}
                DOCFileCode={docFileCode}
                webOfficeRef={ref}
              />
            ) : null}
          </div>
        </Card>
      </Spin>
    </Modal>

  )
}
export default BiddingDocument
