import {BarsOutlined, 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";


interface BiddingAnnouncementProps {
  modalVisible: boolean;
  titleName: string;
  onCancel: () => void;
  type: string;
  tpId: "4419993030303037111";
  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 [TpPackageName, setTpPackageName] = useState<string>("招标");

  const [UploadList, setUploadList] = useState<any>();		//存upload列表
  const [UploadID, setUploadID] = useState<any>(); //upload 业务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>();

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


  /*拉取数据 beg*/
  useEffect(() => {
    Int();
    form.resetFields();//清除form中数据
  }, [pkId, type]);
  useEffect(() => {
    UploadMethod();
  }, [UploadID]);
  const Int = () => {
    setSping(true);
    if (type == "cease") {
      return;
    } else if (type == "new") {//==========================================================新建
      GetPublicityUsablePackage(tpId).then(res => {
        if (res != null && res.message == "success") {
          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("新建")
          setSping(false);
        } else {
          message.error('数据拉取失败：'+res.message);
          onCancel();
        }
      });

      setEditInformation(false);//可编辑
    } else if (type == "edit" || type == "change") {//==========================================================编辑
      GetPublicityUsablePackage(tpId).then(res => {
        if (res != null && res.message == "success") {
          let thisData1 = [];
          for (const item of res.data) {
            thisData1.push({"label": item.bsName, "value": item.bsId})
          }

          GetNoticeMsg(pkId).then(res => {
            if (res != null && res.message == "success") {
              const data = res.data
              for (const item of data.sections) {
                thisData1.push({"label": item.bsName, "value": item.bsId})
              }
              setTpPackageId(thisData1);
              form.setFieldsValue({
                "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
              });
              setUploadID(data.attDatasetId)
              setDocFileCode(data.contentFileId);
              setDocReadOnly("false");
              setDocSaveBtn("compact");
              setDocBtnName("编辑");
              setSping(false);
            } else {
              onCancel();
              message.error('数据拉取失败：'+res.message);
            }
          });
        } else {
          onCancel();
          message.error('数据拉取失败：'+res.message);
        }


      });
      setEditInformation(false);//可编辑
    } else if (type == "read") {//==========================================================查看
      GetNoticeMsg(pkId).then(res => {
        if (res != null && res.message == "success") {
          const data = res.data
          let value = [];
          for (const item of data.sections) {
            value.push({"label": item.bsName, "value": item.bsId})
          }
          setTpPackageId(value);
          form.setFieldsValue({
            "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
          });
          setUploadID(data.attDatasetId)
          setDocFileCode(data.contentFileId);
          setDocReadOnly("true");
          setDocSaveBtn("none");
          setDocBtnName("查看");
          setSping(false);
        } else {
          message.error('数据拉取失败：'+res.message);
          onCancel();
        }
      });
      setEditInformation(true);//只读
    }


  };
  /*拉取数据 end*/


  /*提交数据*/
  const onFinish = (data: any) => {
    if (check("") == "true") {
      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 = {
        "id":pkId,
        "annoNature": 201,
        "tpId": tpId,
        "attDatasetId": UploadID,
        "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,
      }
      creatNotice(type, fromData).then(res => {
        if (res != null && res.message == "success") {
          message.success("成功");
          onCancel();
          SX();
        } else {
          message.error("保存失败:"+res.message);
        }
      });
    }
  }
  /*提交数据 end*/

  /*提交数据校验 beg*/
  const check = (data: any) => {
    let msg = "false";
    if (form.getFieldValue("docStartTime") < moment().format('YYYY-MM-DD')) {
      message.warn('公示开始时间需大于当前时间');
    } else if (moment(form.getFieldValue("docEndTime")).diff(form.getFieldValue("docStartTime"), "days") < 3) {
      message.warn('公示结束时间与公示开始时间需大于3天');
    } else {
      msg = "true"
    }
    return msg;
  }
  /*提交数据校验 end*/


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

  /*upload*/
  const UploadMethod = async () => {
    await getFileBidList(UploadID).then(res => {
      setUploadList(res)
    })
  }
  const UploadOnchange = async (file) => {
    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 testCheck = (checkedParam: any) => {
    if (checkedParam.indexOf("9") > -1) {
      form.setFieldsValue({
        "medias":"9",
      });
      setmediaType(true);
    } else{
      setmediaType(false);
    }

  }
  return (
    <Modal forceRender
           destroyOnClose
           title={titleName}
           visible={modalVisible}
           className="返回"
           onCancel={() => onCancel()}
           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="annoTitle"
            validateStatus="error"
            rules={[
              {
                required: true,
                message: '当前项不可为空',
              },
            ]}
          >
            <Input readOnly={editInformation || editInformation4Change}/>
          </Form.Item>
          <Form.Item
            label={"公示开始时间"}
            name="docStartTime"
            rules={[
              {
                required: true,
                message: '当前项不可为空',
              },
            ]}
          >
            <DatePicker disabled={editInformation || editInformation4Change} format={"yyyy-MM-DD HH:mm:ss"} showTime
                        style={{width: "100%"}}/>
          </Form.Item>
          <Form.Item
            label={"公示结束时间"}
            name="docEndTime"
            rules={[
              {
                required: true,
                message: '当前项不可为空',
              },
            ]}
          >
            <DatePicker disabled={editInformation} showTime style={{width: "100%"}}/>
          </Form.Item>
          <Form.Item
            label="关联标段"
            name="sectionIds"
          >
            {/*标包信息*/}
            <Checkbox.Group
              options={TpPackageId}
              disabled={editInformation || editInformation4Change}
            />
          </Form.Item>
          <Form.Item
            label="附件文件"
            name="attDatasetId"
          >
            <div className={style.bidding}>
              <div className="uploadTotal">
                <Upload
                  action={'/api/core-service-ebtp-updownload/v1/attachment/upload'}
                  data={{"businessId": UploadID}}
                  fileList={UploadList}
                  onChange={UploadOnchange}
                >
                  <Button type="primary" disabled={editInformation || editInformation4Change}
                          className="upload"><UploadOutlined/>上传附件</Button>
                </Upload>
                <p className="uploadLabel">最大能上传10M文件！</p>
              </div>
            </div>
          </Form.Item>

          <Collapse defaultActiveKey={['1', '2']} ghost expandIcon={() => <BarsOutlined/>}>
            <Panel header="公示发布媒体" key="1">
              <Form.Item
                name="medias"
              >
                <Checkbox.Group style={{width: '100%'}} className={style.bidding}
                                onChange={testCheck}
                                disabled={editInformation || editInformation4Change}>

                  <Row>
                    <Col span={24}>
                      <Checkbox disabled={mediaType} key={"1"} value="1">中国联通采购与招标网</Checkbox>
                    </Col>
                    <Col span={24}>
                      <Checkbox disabled={mediaType} key={"2"} value="2">中国采购与招标网</Checkbox>
                    </Col>
                    <Col span={24}>
                      <Checkbox disabled={mediaType} key={"3"} value="3">合作方门户网站</Checkbox>
                    </Col>
                    <Col span={24}>
                      <Checkbox disabled={mediaType} key={"5"} value="5">中国联通电子商城外网接入平台</Checkbox>
                    </Col>
                    <Col span={24}>
                      <Checkbox disabled={mediaType} key={"6"} value="6">中国招标投标公共服务平台</Checkbox>
                    </Col>
                    <Col span={24}>
                      <Checkbox key={"9"} value="9">无需推送至外网媒体</Checkbox>
                    </Col>
                  </Row>
                </Checkbox.Group>
              </Form.Item>
            </Panel>
            <Panel header="公示发布内容" key="2">
              <Card style={{textAlign: "center"}}>
                {docBtnName != "" ? (
                  <Weboffice key={""} memberBtnName={docBtnName} readonly={docReadOnly} btnStyle={docSaveBtn}
                             btnName={"保存"}
                             DocfileCode={docFileCode} PDFfileCode={""} ref={WebofficeRef} onRef={onRef}/>) : null}
              </Card>
            </Panel>
          </Collapse>
        </Form>
      </Card>
    </Spin>
    </Modal>

  )
}


export default BidPublicityResults
