import { UnorderedListOutlined } from "@ant-design/icons"
import ProTable, { ActionType, ProColumns } from "@ant-design/pro-table"
import { Button, Card, Divider, Drawer, message, Modal, Popconfirm, Spin, Table } from "antd"
import React, { useEffect, useRef, useState } from "react"
import {
  GetfileList,
  GetNoticeList,
  removeNotice,
  releaseNotice,
  releaseNoticeAgain,
  ApprovalNotice,
  GetNoticeUsablePackage, GetPublicityUsablePackage, getApprovalFor, over
} from "./service"

import BidPublicityResults from "@/pages/Calibration/BidPublicityResult/components/BidPublicityResults";
import { getDefId, getProId, getProMethod } from "@/utils/session";
import { btnAuthority } from "@/utils/authority";
import { getApprProcessList } from "@/utils/SeleApprovalProcess/service"
import SeleApprovalProcess from "@/utils/SeleApprovalProcess"
import { releaseNoticeOffline } from "@/pages/Bid/BiddingAnnouncement/service"
import { checkObjectId } from "@/utils/DownloadUtils"

/*
* 招标公示开始
*/
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>(10);//当前每页行数


  const [pageloading, setPageloading] = useState<boolean>(false);//加载遮罩
  const [spin, spinSet] = useState<boolean>(false);//遮罩
  const [recordData, setRecordData] = useState<any>({});//存储当前record数据
  const [approvalVisible, setApprovalVisible] = useState<boolean>(false);//选择流程弹窗控制参数
  const [approvalData, setApprovalData] = useState<any[]>([]);//选择流程数据存储

  let name1 = "中标候选人";
  let name2 = "评标";
  let name3 = "开标";
  let name4 = "标段";
  let name5 = '定标';
  let TpPackageName = "";
  let proDict = getProMethod();
  let defId = getDefId();
  if (proDict == "procurement_mode_1" || proDict == "procurement_mode_2") {
    TpPackageName = "招标";
    name1 = "中标候选人";
    name2 = "评标";
    name3 = "开标";
    name4 = "标段";
    name5 = '定标';
  } else if (proDict == "procurement_mode_3") {
    TpPackageName = "比选";
    name1 = "中选候选人";
    name2 = "评审";
    name3 = "评审开始"
    name4 = "采购包";
    name5 = '评审结果';
  } else if (proDict == "procurement_mode_5" || proDict == "procurement_mode_6" || proDict == "procurement_mode_9") {
    TpPackageName = "谈判";
    name1 = "中选候选人";
    name2 = "评审";
    name3 = "评审开始";
    name4 = "采购包";
    name5 = '评审结果';
  } else if (proDict == "procurement_mode_4") {
    TpPackageName = "招募";
    name1 = "招募结果";
    name2 = "评审";
    name3 = "评审开始"
    name4 = "包件";
    name5 = '评审结果';
  } else if (proDict == "procurement_mode_7") {
    TpPackageName = "询价";
    name1 = "中选候选人";
    name2 = "评审";
    name3 = "评审开始";
    name4 = "采购包";
    name5 = '评审结果';
  }


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

    },
    {
      title: name4 + '名称',
      dataIndex: 'sectionNames',
      key: 'sectionNames',
      align: 'left',
    },
    {
      title: '起草时间',
      dataIndex: 'createDate',
      // dataIndex: 'annoStartTime',
      key: "annoStartTime",
      align: 'left',
      valueType: 'dateTime',
    },
    {
      title: '公示状态',
      dataIndex: 'status',
      key: "status",
      align: 'left',
      // valueEnum: {
      //   1: { text: '起草', status: '' },
      //   2: { text: '已提交', status: '' },
      //   3: { text: '已审批', status: '' },
      //   4: { text: '已拒绝', status: '' },
      //   5: { text: '已发布', status: '' },
      //   6: { text: '发布失败', status: '' },
      // },
      render: (_: any, record: any) => {
        let text = ''
        record.status == 1 && (text = '起草');
        record.status == 2 && (text = '已提交');
        record.status == 3 && (text = '已审批');
        record.status == 4 && (text = '已拒绝');
        record.status == 5 && record.publishType == 1 && (text = '线下发布');
        record.status == 5 && (record.publishType == 0 || record.publishType == null) && (text = '发布成功');
        record.status == 6 && (text = '发布失败');
        record.status == 9 && (text = '异常处理');
        return text
      }
    },
    {
      title: '操作',
      dataIndex: 'status',
      key: "",
      align: 'left',
      render: (_: any, record: any) => {
        let btn1 = (
          <>
            <Button hidden={btnAuthority(['ebtp-agency-project-manager', 'ebtp-purchase'])} type="text" onClick={() => toEdit(record)}>编辑</Button>&nbsp;&nbsp;
            <Button hidden={btnAuthority(['ebtp-agency-project-manager', 'ebtp-purchase'])} type="text" disabled={pageloading} onClick={() => handleApproval(record)}>提交审批</Button>&nbsp;&nbsp;
            <Button hidden={btnAuthority(['ebtp-agency-project-manager', 'ebtp-purchase'])} type="text" onClick={() => handleRemove(record)}>删除</Button>
          </>
        );
        let btn2 = (
          <>
            <Button type="text" onClick={() => toRead(record)}>查看</Button>
            <Button type="text" key="9" onClick={() => toApprovalFor(record)} hidden={!checkObjectId(record.id)}>
              查看审批流程
            </Button>
          </>
        );
        let btn3 = (
          <>
            <Button hidden={btnAuthority(['ebtp-agency-project-manager', 'ebtp-purchase'])} type="text" disabled={pageloading} onClick={() => handleRelease(record)}>发布</Button>&nbsp;&nbsp;
            <Button type="text" onClick={() => toRead(record)}>查看</Button>
            <Button type="text" key="9" onClick={() => toApprovalFor(record)} hidden={!checkObjectId(record.id)}>
              查看审批流程
            </Button>
          </>
        );
        let btn4 = (
          <>
            <Button hidden={btnAuthority(['ebtp-agency-project-manager', 'ebtp-purchase'])} type="text" onClick={() => toEdit(record)}>编辑</Button>&nbsp;&nbsp;
            <Button hidden={btnAuthority(['ebtp-agency-project-manager', 'ebtp-purchase'])} type="text" disabled={pageloading} onClick={() => handleApproval(record)}>提交审批</Button>&nbsp;&nbsp;
            <Button type="text" key="9" onClick={() => toApprovalFor(record)} hidden={!checkObjectId(record.id)}>
              查看审批流程
            </Button>
            <Button hidden={btnAuthority(['ebtp-agency-project-manager', 'ebtp-purchase'])} type="text" onClick={() => handleRemove(record)}>删除</Button>
          </>
        );
        let btn5 = (
          <>
            <Button type="text" onClick={() => toRead(record)}>查看</Button>
            <Button type="text" key="9" onClick={() => toApprovalFor(record)} hidden={!checkObjectId(record.id)}>
              查看审批流程
            </Button>
            <Popconfirm
              title={`确定要${name5}结束吗？`}
              onConfirm={async () => {
                spinSet(true);
                await over(record.sectionIds).then((res: any) => {
                  if (res.success) {
                    message.success('已结束！');
                  }
                })
                spinSet(false);
              }}
              okText="确定"
              cancelText="取消"
            >
              <Button hidden={btnAuthority(['ebtp-agency-project-manager', 'ebtp-purchase']) || defId != 'negotiation_single_simple'} type="text" >{name5}结束</Button>
            </Popconfirm>
          </>
        );
        let btn6 = (
          <>
            <Button hidden={btnAuthority(['ebtp-agency-project-manager', 'ebtp-purchase'])} type="text" disabled={pageloading} onClick={() => handleRelease(record)}>发布</Button>&nbsp;&nbsp;
            <Button hidden={btnAuthority(['ebtp-agency-project-manager', 'ebtp-purchase'])} type="text" disabled={pageloading} onClick={() => handleReleaseOffline(record)}>线下发布</Button>
            <Button type="text" onClick={() => toRead(record)}>查看</Button>
            <Button type="text" key="9" onClick={() => toApprovalFor(record)} hidden={!checkObjectId(record.id)}>
              查看审批流程
            </Button>
          </>
        );

        /*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.code == 200) {
          setdataSource(res.data.records)
          setDataSourceAllNum(res.data.total)
        }
      }).finally(() => {
        setPageloading(false);
      })
    }
  }

  /*拉取数据 end*/

  /*新增招标公示*/
  const toEditAdd = (props: any) => {
    GetPublicityUsablePackage(tpId).then(res => {
      if (res != null && res.message == "success") {
        if (res.data.length == 0) {
          message.warn(`没有可关联的${name4}！`)
        } else {
          setPkId("");
          setUpdateChange(`${proDict == "procurement_mode_4" ? '新增' : '新建'}${name1}公示`)
          setType("new");
          setUpdateVisible(true);
        }
      }
    })


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


  /**
   *  删除节点
   * @param selectedRows
   */
  const handleRemove = async (record: any) => {
    setPageloading(true);
    removeNotice(record.id).then(res => {
      if (res.code == 200) {
        message.success('删除成功');
        setRefresh(Math.random() + 1);
      }
    }).finally(() => {
      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.code == 200) {
          message.success('删除成功');
          setRefresh(Math.random() + 1);
        }
      }).finally(() => {
        setPageloading(false);
      });
    }
  };
  /**
   * 发布
   * */
  const handleRelease = async (record: any) => {
    setPageloading(true);
    releaseNotice(record.id).then(res => {
      if (res.code == 200) {
        message.success('发布成功');
        setRefresh(Math.random() + 1);
      }
    }).finally(() => {
      setPageloading(false);
    });
  };
  /**
   * 再次发布
   * */
  const handleReleaseAgain = async (record: any) => {

    setPageloading(true);
    releaseNoticeAgain(record.id).then(res => {
      if (res.code == 200) {
        message.success('发布成功');
        setRefresh(Math.random() + 1);
      }
    }).finally(() => {
      setPageloading(false);
    });
  };
  /**
   *
   * 线下发布
   * */
  const handleReleaseOffline = async (record: any) => {
    setPageloading(true);
    releaseNoticeOffline(record.id).then(res => {
      if (res.code == 200) {
        message.success('发布成功');
        // if (type == "change" || type == "changeNew") {
        //   GetList(FpkId);
        // }
      }
    }).finally(() => {
      setRefresh(Math.random() + 1);
      setPageloading(false);
    });
  };
  /**
   * 发起审批
   * */
  const handleApproval = async (record: any) => {
    setPageloading(true);
    //获取流程列表
    getApprProcessList(record.id).then(res => {
      if (res?.code == 200) {
        const data = res?.data
        if (data?.approval == true) {//打开选择流程界面
          setRecordData(record)
          setApprovalData(data?.list)
          setApprovalVisible(true)
        } else { //直接提交审批
          ApprovalNotice(record.id).then(res => {
            if (res?.code == 200) {
              message.success('发起审批成功');
            }
            setRefresh(Math.random() + 1)
          });
        }
      }
    }).finally(() => {
      setPageloading(false);
    })
  };

  //公示审批单
  const toApprovalFor = async (record: any) => {
    setPageloading(true);
    await getApprovalFor(record.id).then(res => {
      if (res?.code == 200 || res?.success == true) {
        const data = res?.data;
        let durl = /http:\/\/([^\/]+)\//i;
        let d = data?.traceDetailUrl?.replace(durl, '/');
        window.open(d);
      }
    }).finally(() => {
      setPageloading(false);
    });
  }


  return (
    <div style={{ padding: '0px 24px' }}>
      <Spin spinning={spin}>
        <ProTable
          size={"small"}
          loading={pageloading}
          toolBarRender={() => [
            <Button hidden={btnAuthority(['ebtp-agency-project-manager', 'ebtp-purchase'])} key={"1"} type="primary" onClick={() => toEditAdd([])}>{proDict == "procurement_mode_4" ? '新增' : '新建'}{name1}公示</Button>,
            <Button hidden={btnAuthority(['ebtp-agency-project-manager', 'ebtp-purchase'])} 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))
          }}

        />
        {updateVisible ? (
          <BidPublicityResults key={Math.random()} SX={() => setRefresh(Math.random() + 1)} titleName={updateChange}
            pkId={pkId} type={type} tpId={tpId} onCancel={() => setUpdateVisible(false)}
            modalVisible={updateVisible} />
        ) : null}
        {approvalVisible ? (
          <SeleApprovalProcess modalVisible={approvalVisible} onCancel={() => {
            setApprovalVisible(false)
            setApprovalData([])
            setRecordData({})
            setRefresh(Math.random() + 1)
          }} data={approvalData} annoId={recordData?.id} />
        ) : null}
      </Spin>
    </div>
  )
}


export default BidPublicityResult
