import { BarsOutlined, ExclamationCircleOutlined, UploadOutlined } from "@ant-design/icons"
import {
  Button,
  Card, Carousel,
  Checkbox,
  Col,
  Collapse,
  DatePicker, Drawer,
  Form, Image,
  Input, List,
  message,
  Modal, Popover,
  Radio,
  Row,
  Spin,
  Upload
} from "antd"
import React, { useEffect, useRef, useState } from "react"
import style from './style.less'
import { GetNoticeMsg, GetNoticeUsablePackage, creatNotice, getChooseRoom, GetPublicityUsablePackage } from '../service'
import moment from "moment";
import Weboffice from "@/pages/webOffice/weboffice";
import { deleteFileObjId, getFileBidList, SnowflakeID } from "@/services/untilService";
import { getDefId, getProMethod } from "@/utils/session";
import ExtendUpload from "@/utils/ExtendUpload";
import { UploadProps } from "antd/lib/upload/interface";
import Medias from "@/pages/Bid/BiddingAnnouncement/components/Medias"
import BraftText from "@/components/richText/wang";
import RiskPrevention from "@/utils/RiskPrevention"

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

const layout = {
  labelCol: { span: 7 },
  wrapperCol: { span: 10 },
};


const BidPublicityResults: React.FC<BiddingAnnouncementProps> = (props) => {
  const { Panel } = Collapse;
  const { titleName, modalVisible, onCancel, type, tpId, pkId, SX } = props;
  const [form] = Form.useForm();
  const [spinning, setSping] = useState<boolean>(true);//加载遮罩
  const [TpPackageId, setTpPackageId] = useState<any[]>([]); //标包信息
  const [editInformation, setEditInformation] = useState<boolean>(false);//是否可编
  const [editInformation4Change, setEditInformation4Change] = useState<boolean>(false);//是否可编

  const [UploadList, setUploadList] = useState<any>();		//存upload列表
  const [UploadID, setUploadID] = useState<any>(); //upload 业务id
  const [htmlFileCode, setHtmlFileCode] = useState<string>("");//文档id


  const [docFileCode, setDocFileCode] = useState<string>("");//文档id
  const [docBtnName, setDocBtnName] = useState<any>("");//文档按钮文字
  const [docReadOnly, setDocReadOnly] = useState<string>("false");//是否可编辑
  const [docSaveBtn, setDocSaveBtn] = useState<string>("compact");//保存按钮是否展示

  /*20210112 新增 发布媒体限制*/
  const [mediaType, setmediaType] = useState<any>();
  // 2021-06-17 新增 发布媒体显示发布成功失败
  const [mediaReleases, mediaReleasesSet] = useState<any>([]);

  /*weboffice 相关*/
  // const WebofficeRef = useRef<Weboffice>(null);
  // const onRef = (ref) => {
  //   /* this.child= ref;*/
  // }
  // 2021-07-28 新增 富文本
  const braftRef = useRef<any>(null);
  const [echo, echoSet] = useState('')

  const [riskVisible, setRiskVisible] = useState<boolean>(false);//风控弹窗 2021.9.7 zhoujianlong
  const [riskData, setRiskData] = useState<any[]>([]);//风控数据 2021.9.7 zhoujianlong

  const UploadProps: UploadProps = {
    name: "file",
    disabled: editInformation
  }
  let name4 = "标段";
  let TpPackageName = "";
  let proDict = getProMethod();
  let defId = getDefId();
  let intervalDate = defId == 'negotiation_single' ? '1' : '3' //20210622 zhoujianlong新增日期间隔参数
  if (proDict == "procurement_mode_1" || proDict == "procurement_mode_2") {
    TpPackageName = "招标";
    name4 = "标段";
  } else if (proDict == "procurement_mode_3") {
    TpPackageName = "比选";
    name4 = "采购包";

  } else if (proDict == "procurement_mode_5" || proDict == "procurement_mode_6") {
    TpPackageName = "谈判";
    name4 = "采购包";

  } else if (proDict == "procurement_mode_4") {
    TpPackageName = "招募";
    name4 = "包件";
  } else if (proDict == "procurement_mode_7") {
    TpPackageName = "询价";
    name4 = "包件";
  }




  /*拉取数据 beg*/
  useEffect(() => {
    Int();
    form.resetFields();//清除form中数据
  }, [pkId, type]);
  const Int = async () => {
    setSping(true);
    if (type == "cease") {
      return;
    } else if (type == "new") {//==========================================================新建
      GetPublicityUsablePackage(tpId).then(res => {
        if (res.code == 200) {
          let value = [];
          for (const item of res.data) {
            value.push({ "label": item.bsName, "value": item.bsId })
          }
          SnowflakeID().then(res => {
            setUploadID(res.id);
          });
          setTpPackageId(value);
          setDocReadOnly("false");
          setDocSaveBtn("compact");
          setDocBtnName("新建")
        }
      }).finally(() => {
        setSping(false);
      });

      setEditInformation(false);//可编辑
    } else if (type == "edit" || type == "change") {//==========================================================编辑

      await GetPublicityUsablePackage(tpId, pkId).then(res => {
        if (res.code == 200) {
          let thisData1 = [];
          for (const item of res.data) {
            thisData1.push({ "label": item.bsName, "value": item.bsId })
          }
          setTpPackageId(thisData1);
        }
      });
      GetNoticeMsg(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({
            "attDatasetId": data.attDatasetId,
            "docStartTime": moment(data.docStartTime, 'yyyy-MM-DD HH:mm:ss'),
            "docEndTime": moment(data.docEndTime, 'yyyy-MM-DD HH:mm:ss'),
            "annoTitle": data.annoTitle,
            "medias": data.medias,
            "sectionIds": defPak
          });
          echoSet(data.contentWithStyle);
          setUploadID(data.attDatasetId);
          setHtmlFileCode(data.contentHtmlId)
          setDocFileCode(data.contentFileId);
          setDocReadOnly("false");
          setDocSaveBtn("compact");
          setDocBtnName("编辑");
        }
      }).finally(() => {
        setSping(false);
      });
      setEditInformation(false);//可编辑
    } else if (type == "read") {//==========================================================查看
      GetNoticeMsg(pkId).then(res => {
        if (res.code == 200) {
          const data = res.data
          let value = [];
          for (const item of data.sections) {
            value.push({ "label": item.bsName, "value": item.bsId })
          }
          setTpPackageId(value);
          form.setFieldsValue({
            "attDatasetId": data.attDatasetId,
            "docStartTime": moment(data.docStartTime, 'yyyy-MM-DD HH:mm:ss'),
            "docEndTime": moment(data.docEndTime, 'yyyy-MM-DD HH:mm:ss'),
            "annoTitle": data.annoTitle,
            "medias": data.medias,
            "sectionIds": data.sectionIds
          });
          echoSet(data.contentWithStyle);
          setUploadID(data.attDatasetId);
          setDocFileCode(data.contentFileId);
          mediaReleasesSet(data.mediaReleases);
          setDocReadOnly("true");
          setDocSaveBtn("none");
          setDocBtnName("查看");
        }
      }).finally(() => {
        setSping(false);
      });
      setEditInformation(true);//只读
    }


  };
  /*拉取数据 end*/


  /*提交数据*/
  const onFinish = (data: any) => {
    form.validateFields().then(() => {
      check();
    })

    // if (checkResult) {
    //   saveData()
    // }
  }
  //提交数据复用方法
  const saveData = () => {
    setSping(true);
    const packageMsg = [];

    for (const item of TpPackageId) {//包数据
      if (form.getFieldValue("sectionIds")) {
        if (Array.isArray(form.getFieldValue("sectionIds"))) {
          for (const item1 of form.getFieldValue("sectionIds")) {
            if (item.value == item1) {
              packageMsg.push({ "bsId": item.value, "bsName": item.label })
            }
          }
        } else {
          if (item.value == form.getFieldValue("sectionIds")) {
            packageMsg.push({ "bsId": item.value, "bsName": item.label })
          }
        }
      } else {
        message.warn("您未选择" + name4);
        setSping(false);
      }

    }

    if (type == "new" || type == "changeNew" || type == 'edit') {//==========================================================新建
      if (braftRef.current.getHtml() == '') {
        message.warn("您尚未编辑公示内容");
        setSping(false);
        return;
      }
    }
    const fromData = {
      "id": pkId,
      "annoNature": 201,
      "tpId": tpId,
      "attDatasetId": form.getFieldValue("attDatasetId"),//
      "contentWithStyle": braftRef.current.getHtml().replace(/<table border="0"/, '<table border="1"'),//富文本正文
      "source": 12,//来源（1：预审公示；2：预审公示；11：资审公示；12资审公示；21：邀请函）
      "annoTitle": form.getFieldValue("annoTitle"),
      "docStartTime": form.getFieldValue("docStartTime").format("yyyy-MM-DD HH:mm:ss").toString(),
      "docEndTime": form.getFieldValue("docEndTime").format("yyyy-MM-DD HH:mm:ss").toString(),
      "medias": form.getFieldValue("medias").toString(),
      "sections": packageMsg,
      // "contentFileId": WebofficeRef.current!.DocfileCode,
      // "contentHtmlId": WebofficeRef.current!.HTMLfileCode,//html id

    }

    creatNotice(type, fromData).then(res => {
      if (res?.code == 4004 && res?.success == false) { //2021.9.7 zhoujianlong 新增和修改公示增加风控
        const data = res?.data?.result == undefined ? [] : res?.data?.result
        setRiskData(data)
        setRiskVisible(true)
      }
      if (res.code == 200) {
        message.success("成功");
        onCancel();
        SX();
      }
    }).finally(() => {
      setSping(false);
    });
  }
  /*提交数据 end*/

  /*提交数据校验 beg*/
  const check = () => {
    if (form.getFieldValue("docStartTime") < moment().startOf('day')) {
      message.warn('公示开始时间需大于当前时间');
    } else {
      if (defId == 'negotiation_single') {
        if (moment(form.getFieldValue("docEndTime")).startOf('day').diff(moment(form.getFieldValue("docStartTime")).startOf('day'), "days") < 1) { //20210622 zhoujianlong 修改单一来源时间校验为大于一天
          message.warn('公示结束时间需要在公示开始时间的1天以后');
        } else {
          saveData()
        }
      } else {
        if (moment(form.getFieldValue("docEndTime")).startOf('day').diff(moment(form.getFieldValue("docStartTime")).startOf('day'), "days") < 3) {
          message.warn('公示结束时间需要在公示开始时间的3天以后');
        } else {
          saveData()
        }
      }
    }
  }

  /*提交数据校验 end*/


  const renderFooter = () => {
    if (type == "read") {
      return (
        <>
          <Button onClick={onCancel}>关闭</Button>
        </>
      );
    } else {
      return (
        <>
          <Button type="primary" onClick={onFinish}>确认</Button>
          <Button onClick={onCancel}>取消</Button>
        </>
      );
    }
  }

  /*upload*/
  const UploadMethod = async () => {
    await 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("上传失败");
    }
  }

  //修改发布媒体 触发方法-邢书源
  const medias9 = (dis: any) => {
    if (dis) {
      form.setFieldsValue({
        "medias": "9",
      });
    }
    setmediaType(dis);
  }

  const testCheck = (checkedParam: any) => {
    if (checkedParam.indexOf("9") > -1) {
      form.setFieldsValue({
        "medias": "9",
      });
      setmediaType(true);
    } else {
      setmediaType(false);
    }

  }
  const modalHeight = (window.innerHeight * 96) / 100;
  return (
    <Modal forceRender
      destroyOnClose
      title={titleName}
      visible={modalVisible}
      className="返回"
      onCancel={() => onCancel()}
      width={"60%"}
      style={{ maxHeight: modalHeight }}
      bodyStyle={{ maxHeight: modalHeight - 107, overflowY: 'auto' }}
      centered
      footer={renderFooter()}
    ><Spin spinning={spinning}>
        <div>
          <Form
            {...layout}
            name="basic"
            form={form}
          >

            <Form.Item
              label="公示名称"
              name="annoTitle"
              rules={[
                {
                  required: true,
                  message: '当前项不可为空',
                },
              ]}
            >
              <Input maxLength={200} readOnly={editInformation || editInformation4Change} />
            </Form.Item>
            <Form.Item
              label={"公示开始时间"}
              name="docStartTime"
              rules={[
                {
                  required: true,
                  message: '当前项不可为空',
                },
              ]}
            >
              <DatePicker showNow={false} disabled={editInformation || editInformation4Change} format={"yyyy-MM-DD HH:mm"} showTime={{ defaultValue: moment().startOf('minute') }} disabledDate={(current) => current && current < moment().startOf('day')}
                style={{ width: "100%" }} />
            </Form.Item>
            <Form.Item
              label={"公示结束时间"}
              name="docEndTime"
              rules={[
                {
                  required: true,
                  message: '当前项不可为空',
                },
              ]}
              extra={`公示结束时间需要在公示开始时间的${intervalDate}天以后`}
            >
              <DatePicker showNow={false} disabled={editInformation} showTime={{ defaultValue: moment().startOf('minute') }} format={"yyyy-MM-DD HH:mm"} style={{ width: "100%" }} />
            </Form.Item>
            <Form.Item
              label={"关联" + name4}
              name="sectionIds"
              rules={[
                {
                  required: true,
                  message: '当前项不可为空',
                },
              ]}
            >
              {/*标包信息*/}
              <Checkbox.Group
                options={TpPackageId}
                disabled={editInformation || editInformation4Change}
              />
            </Form.Item>
            <Form.Item
              label="附件文件"
              name="attDatasetId"
              extra="单个附件最大30MB"
            >
              {UploadID != "empty" ? <ExtendUpload uploadProps={UploadProps} maxCount={3} bid={UploadID} /> : null}
            </Form.Item>

            {/* 发布媒体 */}
            <Medias
              vis={modalVisible}
              h3Vis={true}
              editInformation={editInformation}
              editInformation4Change={editInformation4Change}
              mediaType={mediaType}
              mediaReleases={mediaReleases}
              medias9={(dis: boolean) => medias9(dis)}
            />
            <h3 className="first-title">公示发布内容</h3>
            {/* <Card style={{ textAlign: "center" }}> */}
            {/* {docBtnName != "" ? (
                <Weboffice key={""} memberBtnName={docBtnName} readonly={docReadOnly} btnStyle={docSaveBtn}
                  btnName={"保存"}
                  DocfileCode={docFileCode} PDFfileCode={""} HTMLfileCode={htmlFileCode} saveHTML={"1"} ref={WebofficeRef} onRef={onRef} />) : null} */}
            <BraftText braftRef={braftRef} echo={echo} disabled={editInformation} />
            {/* </Card> */}
          </Form>
          {/**风控组件 */}
          {riskVisible && <RiskPrevention
            modalVisible={riskVisible}
            onCancel={() => {
              setRiskVisible(false)
              setRiskData([])
            }}
            data={riskData}
          />}
        </div>
      </Spin>
    </Modal>

  )
}


export default BidPublicityResults
