import { UnorderedListOutlined } from "@ant-design/icons"
import ProTable, {ActionType, ProColumns} from "@ant-design/pro-table"
import {Button, Card, Divider, Drawer, message, Modal, Spin, Table} from "antd"
import React, {useEffect, useRef, useState} from "react"
import {
  GetfileList,
  GetNoticeList,
  removeNotice,
  releaseNotice,
  releaseNoticeAgain,
  ApprovalNotice,
  GetNoticeUsablePackage, GetPublicityUsablePackage
} from "./service"
import style from "./components/style.less"
import BidPublicityResults from "@/pages/Calibration/BidPublicityResult/components/BidPublicityResults";
import {getProId} from "@/utils/session";

/*
* 招标公示开始
*/
interface DataItem {
  key:number,
  announcementName: string,
  associatedPackage: string,
  writeTime: Date,
  announcementState: string,
  onSubmit: (values: any) => void;//点击保存的回调
}


const BidPublicityResult: React.FC<{}> = (props) => {
  const [Refresh, setRefresh] = useState<any>(Math.random);
  const [selectedRowsState, setSelectedRows] = useState<DataItem[]>([]);
  const [updateVisible, setUpdateVisible] = useState<boolean>(false)
  const [updateChange, setUpdateChange] = useState<string>('');//弹窗名
  const [type, setType] = useState<any>('cease');//弹窗类型
  const [pkId,setPkId] =useState<string>();//公示/邀请函id
  const [tpId,setTpId] = useState<any>(getProId);//项目id
  const [dataSource,setdataSource]= useState<any[]>([]); //公示列表数据
  const [dataSourcePage,setDataSourcePage] = useState<any>(1);//当前页数
  const [dataSourceAllNum,setDataSourceAllNum] = useState<any>();//总行数
  const [dataSourceNum,setDataSourceNum] = useState<any>(20);//当前每页行数
  const [ChangeNoticeListVisible,setChangeNoticeListVisible] =useState<boolean>(false); //变更公示列表窗状态
  const [ChangeNoticeListdataSource,setChangeNoticeListdataSource]= useState<any[]>([]); //变更公示列表数据

  const [pageloading,setPageloading]=useState<boolean>(false);//加载遮罩



  const columns: ProColumns<DataItem>[] = [
    {
      title: '公示名称',
      dataIndex: 'annoTitle',
      key:'annoTitle',
      align:'center',

    },
    {
      title: '关联标段',
      dataIndex: 'sectionNames',
      key:'sectionNames',
      align:'center',
    },
    {
      title: '起草时间',
      dataIndex: 'annoStartTime',
      key:"annoStartTime",
      align:'center',
      valueType: 'dateTime',
    },
    {
      title: '公示状态',
      dataIndex: 'status',
      key:"status",
      align:'center',
      valueEnum: {
        1: { text: '起草', status: '' },
        2: { text: '已提交', status: '' },
        3: { text: '已审批', status: '' },
        4: { text: '已拒绝', status: '' },
        5: { text: '已发布', status: '' },
        6: { text: '发布失败', status: '' },
      },
    },
    {
      title: '操作',
      dataIndex: 'status',
      key:"",
      align:'center',
      render: (_:any, record: any) => {
        let btn1= (
          <>
            <a onClick={() => toEdit(record)}>编辑</a><Divider type="vertical"/>
            <a onClick={() => handleApproval(record)}>提交审批</a><Divider type="vertical"/>
            <a onClick={() => handleRemove(record)}>删除</a>
          </>
        );
        let btn2= (
          <>
            <a onClick={() => toRead(record)}>查看</a><Divider type="vertical"/>
          </>
        );
        let btn3= (
          <>
            <a onClick={() => handleRelease(record)}>发布</a><Divider type="vertical"/>
            <a onClick={() => toRead(record)}>查看</a>
          </>
        );
        let btn4= (
          <>
            <a onClick={() => toEdit(record)}>编辑</a><Divider type="vertical"/>
            <a onClick={() => handleApproval(record)}>提交审批</a><Divider type="vertical"/>
            <a onClick={() => handleRemove(record)}>删除</a>
          </>
        );
        let btn5= (
          <>
            <a onClick={() => toRead(record)}>查看</a><Divider type="vertical"/>
            <a onClick={() => handleReleaseAgain(record)}>再次发布</a><Divider type="vertical"/>
          </>
        );
        let btn6= (
          <>
            <a onClick={() => handleRelease(record)}>发布</a><Divider type="vertical"/>
            <a onClick={() => toRead(record)}>查看</a>
          </>
        );

        /*if(true){
          return btn3;
        }else*/ if(record.status==1){
          return btn1;
        }else if(record.status==2){
          return btn2;
        }else if(record.status==3){
          return btn3;
        }else if(record.status==4){
          return btn4;
        }else if(record.status==5){
          return btn5;
        }else if(record.status==6){
          return btn6;
        } else {
          return (<></>)
        }
      },





    },
  ];

  /*拉取数据 beg*/
  useEffect(()=>{
    GetList("page")
  },[tpId,dataSourceNum,dataSourcePage,Refresh])

  const GetList = (props: any)=>{
    setPageloading(true);
    if(props=="page"){//初始化页面
      GetNoticeList({
        "annoNature": 201,
        "annoTitle": "",
        "csAnnoId": "",
        "pageNo": dataSourcePage,
        "pageSize":dataSourceNum,
        "source": 12,
        "tpId": tpId
      }).then(res => {
        if(res!=null&&res.message=="success"){
          setdataSource(res.data.records)
          setDataSourceAllNum(res.total)
        } else{
          message.error('程序出错，亲您稍后在世');
        }
        setPageloading(false);
      })
    }
  }

  /*拉取数据 end*/

  /*新增招标公示*/
  const toEditAdd = (props: any) => {
    GetPublicityUsablePackage(tpId).then(res=>{
      if (res != null && res.message == "success") {
        if (res.data.length == 0) {
          message.warn("没有可关联的标段！")
        }else{
          setUpdateVisible(true);
          setUpdateChange('新建中标候选人公示')
          setType("new");
        }
      }else {
        message.error("查询标段信息失败："+res.message)
      }
    })



  }
  /*编辑招标公示*/
  const toEdit = (props: any) => {
    setUpdateVisible(true);
    setUpdateChange('编辑招标公示')
    setPkId(props.id);
    setType("edit");
  }
  /*查看招标公示*/
  const toRead = (props: any) => {
    setUpdateVisible(true);
    setUpdateChange('查看招标公示')
    setType("read");
    setPkId(props.id);
  }





  /**
   *  删除节点
   * @param selectedRows
   */
  const handleRemove = async (record: any) => {
    setPageloading(true);
    removeNotice(record.id).then(res=>{
      if(res!=null&&res.message=="success"){
        message.success('删除成功');
        setRefresh(Math.random()+1);
      }else {
        message.error("删除失败："+res.message);
      }
      setPageloading(false);
    });

  };
  /**
   * 批量删除
   * */
  const handleRemoveMore = async () => {
    if(selectedRowsState.length!=0){
      setPageloading(true);
      let param=[]
      for(const item of selectedRowsState){
        param.push(item.id);
      }
      removeNotice(param).then(res=>{
        if(res!=null&&res.data){
          message.success('删除成功');
          setRefresh(Math.random()+1);
        }else {
          message.error("删除失败："+res.message);
        }
        setPageloading(false);

      });
    }
  };
  /**
   * 发布
   * */
  const handleRelease = async (record:any) => {
    setPageloading(true);
    releaseNotice(record.id).then(res=>{
      if(res!=null&&res.data){
        message.success('发布成功');
        setRefresh(Math.random()+1);
      }else {
        message.error('发布失败：'+res.message);
      }
      setPageloading(false);
    });
  };
  /**
   * 再次发布
   * */
  const handleReleaseAgain = async (record:any) => {

    setPageloading(true);
    releaseNoticeAgain(record.id).then(res=>{
      if(res!=null&&res.data){
        message.success('发布成功');
        setRefresh(Math.random()+1);
      }else {
        message.error('发布失败：'+res.message);
      }
      setPageloading(false);
    });
  };
  /**
   * 发起审批
   * */
  const handleApproval = async (record:any) => {
    setPageloading(true);
    ApprovalNotice(record.id).then(res=>{
      if(res!=null&&res.data){
        message.success('发起审批成功');
        setRefresh(Math.random()+1);
      }else {
        message.error('发起审批失败：'+res.message);
      }
      setPageloading(false);
    });
  };


  return (
    <>

      <Card>
        <Divider style={{margin: "8px 0px"}}/>
        <div className={style.label}>
          <UnorderedListOutlined style={{marginRight: "8px"}}/>招标公示信息
        </div>
        <ProTable
          loading={pageloading}
          toolBarRender={() => [
            <Button key={"1"} type="primary"  onClick={() => toEditAdd([])}>新建中选候选人公示</Button>,
            <Button key={"2"} onClick={()=>{handleRemoveMore()}}>批量删除</Button>,
          ]}
          search={false}
          options={false}
          columns={columns}
          dataSource={dataSource}
          rowKey={"id"}
          rowSelection={{
            onChange: (_, selectedRows) => setSelectedRows(selectedRows),
          }}

          pagination={{
            pageSize:dataSourceNum,
            current:dataSourcePage,
            total: dataSourceAllNum,
            pageSizeOptions:['10','20','50'],
            onShowSizeChange:((current, size)=>setDataSourceNum(size)),
            onChange:((page, pageSize)=>setDataSourcePage(page))
          }}

        />

      </Card>
      {updateVisible?(
      <BidPublicityResults SX={()=>setRefresh(Math.random()+1)} titleName={updateChange} pkId={pkId}  type={type} tpId={tpId}  onCancel={() => setUpdateVisible(false)} modalVisible={updateVisible} />
      ):null}
      </>
  )
}


export default BidPublicityResult
