import ProTable, { ActionType, } from "@ant-design/pro-table";
import { Button, Col, Descriptions, Form, Input, message, Modal, Progress, Row, Spin } from "antd";
import React, { useEffect, useRef, useState } from "react";
import styles from './index.less';
import './index.less';
import { getList, jieMi, jmRate, singBid, endTimeUp, updatePrice, queryFx, confirmOffer } from './service';
import { getSessionUserData, } from '@/utils/session';

const Room: React.FC<{}> = () => {
  const [spin, spinSet] = useState<any>(false);
  const FormItem = Form.Item;
  const { TextArea } = Input;
  const formLayout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
  };
  //控制字段  角色、开标状态、唱标阶段、是否需要ipass解密
  // const proId = 1111111;
  const juese = getSessionUserData().roleIds//daili 代理 gys 供应商
  const actionRef = useRef<ActionType>();
  const [count, countSet] = useState<number>(0); //开标室启动器
  // const [turnSort, turnSortSet] = useState<number>(1); //开标室启动器
  const [projectName, projectNameSet] = useState<any>(''); //项目名称
  const [projectNo, projectNoSet] = useState<any>(''); //项目编号
  const [sectionName, sectionNameSet] = useState<any>(''); //标包名称
  const [sectionNo, sectionNoSet] = useState<any>(''); //标包编号
  const [openTime, openTimeSet] = useState<any>(''); //开标时间
  const [openState, openStateSet] = useState<boolean>();//是否开标
  const [range, rangeSet] = useState<boolean>();//是否唱标
  const [jm, jmSet] = useState<boolean>();//是否解密
  const [rangeOver, rangeOverSet] = useState<boolean>();//是否唱标结束
  const [important, importantSet] = useState<boolean>();//是否重大项目
  const [turnId, turnIdSet] = useState<any>('');//轮次id
  const [configId, configIdSet] = useState<any>('');//唱标配置id
  const [openRoom, openRoomSet] = useState<any>('');//开标室id

  const [repairVis, repairVisSet] = useState<boolean>(false);//补录报价显隐
  const [subentryVis, handleSubentryVis] = useState<boolean>(false);//分项报价显隐
  const [tdocId, tdocIdSet] = useState<any>('');//tdocId  分项报价表用
  const [jmTimeVis, jmTimeVisSet] = useState<boolean>(false);//解密时限显隐
  const [endTime, endTimeSet] = useState<any>();//解密时限
  const [rateVis, handleRateVis] = useState<boolean>(false); //进度显隐
  const [rateCount, rateCountSet] = useState<number>(0); //查询进度启动器
  const [jmFileCount, jmFileCountSet] = useState<number>(0);//文件总数
  const [jmComplete, jmCompleteSet] = useState<number>(0);//已解密成功
  const [jmWait, jmWaitSet] = useState<number>(0);//未解密
  const [jmFail, jmFailSet] = useState<number>(0);//解密失败


  const [dis, disSet] = useState<boolean>(false);//解密失败

  //开标室表格
  const [columnsKb, columnsKbSet] = useState<any>([]);
  const [columnsKbData, columnsKbDataSet] = useState<any>([]);

  //解密
  const sing = async (fields: any) => {
    const hide = message.loading('正在配置');
    try {
      await singBid({ ...fields });
      hide();
      message.success('成功！');
      getTableData();
      return true;
    } catch (error) {
      hide();
      message.error('失败请重试！');
      return false;
    }
  };
  //设置解密时限
  const endTimeConfig = async (fields: any) => {
    const hide = message.loading('正在配置');
    try {
      await endTimeUp({ ...fields });
      hide();
      message.success('配置成功！');
      return true;
    } catch (error) {
      hide();
      message.error('配置失败请重试！');
      return false;
    }
  };
  //开标室表格按钮
  const tools = [
    juese === 'daili' && !important && !range ? <Button key='jm' type="primary" onClick={() => { jmTimeVisSet(true) }}>设置投标人解密时限</Button> : null,
    juese === 'daili' && !range && jmComplete != jmFileCount  ?
      <Button key='jm' type="primary" disabled={dis}
        onClick={async () => {
          spinSet(true); disSet(true);
          const success = await jieMi({ tdocId: tdocId });
          if (success) {
            handleRateVis(true);
            rateCountSet(rateCount + 1);
          }
          spinSet(false); disSet(false);
        }}>解密</Button> : null,
    juese === 'daili' && !range && jmComplete != jmFileCount?
      <Button key='ckjd' type="primary" disabled={dis}
        onClick={() => {
          disSet(true);
          handleRateVis(true);
          rateCountSet(rateCount + 1);
          disSet(false);
        }}>查看解密进度</Button> : null,
    juese === 'daili' && (jmComplete + jmFail) > 0 && !rangeOver && !range ?
      <Button disabled={dis} key='cb' type="primary" onClick={async () => {
        disSet(true);
        await sing({ id: configId, whetherRange: 1 });
        disSet(false);
      }}>唱标</Button> : null,
    juese === 'daili' && range && !rangeOver ?
      <Button disabled={dis} key='cbjs' type="primary" onClick={async () => {
        disSet(true);
        await sing({ id: configId, whetherRangeOver: 1 });
        disSet(false);
      }}>唱标结束</Button> : null,
    juese === 'gys' && range && !rangeOver ?
      <Button key='qrbj' type="primary" disabled={dis}
        onClick={async () => {
          disSet(true);
          await confirmOffer(turnId).then((res) => {
            console.log(res);
            if (res.message === 'success') {
              message.success('确认成功')
            }
          })
          disSet(false);
        }}>确认报价</Button> : null,
    juese === 'daili' ? <Button key='dy' type="primary" onClick={() => { }}>打印</Button> : null,
  ];
  //取参数
  function getQueryString(name: any) {
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    let r = window.location.search.substr(1).match(reg);
    return r !== null ? unescape(r[2]) : null;
  }
  //进页面执行
  useEffect(() => {
    getTableData();
  }, [count]);
  //查询进度
  useEffect(() => {
    if (rateVis) {
      queryRate();
      setTimeout(async () => {
        rateCountSet(rateCount + 1);
      }, 2000);
    }
  }, [rateCount]);
  async function queryRate() {//查询解密进度
    let all: number, comp: number, fail: number, wait: number = 0;
    await jmRate({ tdocId: tdocId }).then((res) => {
      // console.log(res);
      let data = res.data;
      if (data != undefined) {
        all = data['-1'] != undefined ? data['-1'] : 0;
        comp = data['1'] != undefined ? data['1'] : 0;
        fail = data['2'] != undefined ? data['2'] : 0;
        wait = data['0'] != undefined ? data['0'] : 0;
      }
      jmCompleteSet(comp);
      jmFailSet(fail);
      jmFileCountSet(all);
      jmWaitSet(wait);
    });
  }
  //取表格数据
  const getTableData = async () => {

    let assessRoomId: any = "";
    let turnSort: any = '';
    let commpanyId = getSessionUserData().organizationId;
    juese == 'daili' ? commpanyId = '' : null;
    if (getQueryString("aa") != null) {
      assessRoomId = getQueryString("aa")
    }
    if (getQueryString("bb") != null) {
      turnSort = getQueryString("bb")
    }

    let column: any = [];
    let data: any = [];
    let category: any[] = [];
    let projectName: any, projectNo: any, sectionName: any, sectionNo: any, openTime: any, turnId: any, configId: any, openRoomId: any, tdocId: any = '';
    let openState: any, decryptStatus: any, important: any = false;
    let rangeT: any, rangeOverT: any = true;
    await getList({ assessRoomId: assessRoomId, turnSort: turnSort, commpanyId: commpanyId }).then((res) => {
      // console.log(res);
      //拼记录表信息
      if (res.data != undefined) {
        projectName = res.data.singConfig.projectName;
        projectNo = res.data.singConfig.projectNo;
        sectionName = res.data.singConfig.sectionName;
        sectionNo = res.data.singConfig.sectionNo;
        openTime = res.data.singConfig.openTime;
        openState = res.data.singConfig.openState == 1 || res.data.singConfig.openState == 3 ? true : false;

        rangeT = res.data.singConfig.whetherRange == 1 ? true : false;
        rangeOverT = res.data.singConfig.whetherRangeOver == 1 ? true : false;
        decryptStatus = res.data.singConfig.decryptStatus == 1 ? true : false;
        important = res.data.singConfig.passDecode == 1 ? true : false;
        turnId = res.data.singConfig.turnId;
        configId = res.data.singConfig.id;
        openRoomId = res.data.singConfig.openRoomId;
        important = res.data.singConfig.passDecode == 1 ? true : false;
      }
      if (res.data != undefined) {
        //拼表格
        column.push({ title: '序号', dataIndex: 'index', valueType: 'index', });
        column.push({ title: '投标单位', dataIndex: 'companyName', });
        res.data.title.map((item: any, index: any) => {
          column.push({ title: item.name, dataIndex: item.id, });
          category.push(item.id);
        });
        column.push({ title: '签名信息', dataIndex: 'bidUserName', width: 200, });
        column.push({
          title: '操作', dataIndex: 'option', width: 250,
          valueType: 'option',
          render: (_: any, record: any) => {
            // console.log(record);

            return (
              <>
                {
                  juese === 'daili' && rangeT && record.quoteId != null ?
                    <><Button key='ckfxbj' onClick={() => { queryFxbj(record,tdocId); handleSubentryVis(true); }}>查看分项报价</Button>&nbsp;&nbsp;</>
                    : null
                }
                {
                  juese === 'daili' && rangeT && !rangeOverT && record.quoteDecryptStatus == 2 && record.quoteId != null ? <>
                    <Button key='blbj' type="primary" onClick={() => {
                      repairVisSet(true);
                      formBlbj.setFieldsValue({
                        companyName: record.companyName,
                        sectionName: record.sectionName,
                        tendererId: record.tendererId,
                        contentDataId: record.contentDataId,
                      })
                    }} >补录报价</Button></>
                    : null
                }
                {/* <a onClick={()=>console.log(record)}>aaaa</a> */}
              </>
            )
          }
        });
        //拼data
        res.data.suppliers != undefined ? res.data.suppliers.map((item1: any, index: any) => {
          let oneGys = {};
          item1.signTime == null ? item1.signTime = '未签名' : null;
          oneGys["key"] = index;
          oneGys["companyName"] = item1.companyName;
          oneGys["bidUserName"] = item1.bidUserName + "(" + item1.signTime + ")";
          oneGys["sectionName"] = sectionName;
          oneGys["tendererId"] = item1.id;//投标人id，补录报价用
          oneGys["contentDataId"] = item1.quoteId;//数据表id，补录报价用
          oneGys["quoteDecryptStatus"] = item1.quoteDecryptStatus;
          oneGys["quoteId"] = item1.quoteId;
          category.map((item2: any, index: any) => {
            oneGys[item2] = item1.dataMap[item2];
          });
          data.push(oneGys);
        }) : null;


        //取tdoc id 分项报价用
        tdocId = res.data.tdoc.id;
      }
      columnsKbSet(column);
      columnsKbDataSet(data);
      projectNameSet(projectName);
      projectNoSet(projectNo);
      sectionNameSet(sectionName);
      sectionNoSet(sectionNo);
      openTimeSet(openTime);
      openStateSet(openState);
      rangeSet(rangeT);
      rangeOverSet(rangeOverT);
      jmSet(decryptStatus);
      turnIdSet(turnId);
      configIdSet(configId);
      openRoomSet(openRoomId);
      importantSet(important);
      tdocIdSet(tdocId);
    });
    //查询进度
    let all: number, comp: number, fail: number, wait: number = 0;
    await jmRate({ tdocId: tdocId }).then((res) => {
      // console.log(res);
      let data = res.data;
      if (data != undefined) {
        all = data['-1'] != undefined ? data['-1'] : 0;
        comp = data['1'] != undefined ? data['1'] : 0;
        fail = data['2'] != undefined ? data['2'] : 0;
        wait = data['0'] != undefined ? data['0'] : 0;
      }
      jmCompleteSet(comp);
      jmFailSet(fail);
      jmFileCountSet(all);
      jmWaitSet(wait);
    });
    console.log(tdocId);
    
    //供应商未唱标结束就轮询  代理唱标后到唱标结束之前轮询
    if ((juese === 'gys' && !rangeOverT) || (juese === 'daili' && !rangeOverT && rangeT)) {
      setTimeout(() => {
        countSet(count + 1);
      }, 3000);
    }
  }
  //开标记录表
  const kbjl = () => {
    return (
      <>
        <div className={styles.titleTop}>
          <div style={{ backgroundColor: 'white' }}><span style={{ letterSpacing: "50px" }}>开标报价记录</span>表</div>
        </div>
        <div className="desStyle">
          <Descriptions bordered column={2} size="small">
            <Descriptions.Item label="项目名称" className={styles.desItemStyle} span={2}>{projectName}</Descriptions.Item>
            <Descriptions.Item label="项目编号" className={styles.desItemStyle}>{projectNo}</Descriptions.Item>
            <Descriptions.Item label="标包名称" className={styles.desItemStyle}>{sectionName}</Descriptions.Item>
            <Descriptions.Item label="标段编号" className={styles.desItemStyle}>{sectionNo}</Descriptions.Item>
            <Descriptions.Item label="开标时间" className={styles.desItemStyle}>{openTime}</Descriptions.Item>
          </Descriptions>
        </div>
        <ProTable
          actionRef={actionRef}
          columns={columnsKb}//表格
          dataSource={columnsKbData}
          search={false}
          size={'small'}
          rowSelection={false}
          toolBarRender={() => tools}
          pagination={false}
        />
      </>
    )
  }
  //补录报价
  const [formBlbj] = Form.useForm();
  const blbj = () => {
    return (
      <Modal
        title="补录报价"
        width={'800px'}
        destroyOnClose
        centered
        bodyStyle={{ padding: '32px 40px 48px', overflowY: 'auto' }}
        visible={repairVis}
        onCancel={() => repairVisSet(false)}
        onOk={async () => {
          // console.log(formBlbj.getFieldsValue());
          spinSet(true);
          let verify = false;
          await formBlbj.validateFields().then(() => {
            verify = true;
          }).catch((errorInfo) => {
            console.log(errorInfo);
          });
          if (verify) {
            const { newPrice, contentDataId, tendererId } = formBlbj.getFieldsValue();
            const success = await updatePrice({ newPrice: newPrice, contentDataId: contentDataId, tendererId: tendererId, tdocId: tdocId });
            if (success) {
              message.success('补录成功!');
              repairVisSet(false);
            } else {
              message.error('补录失败!')
            }
            getTableData();
          }
          spinSet(false);
        }}
      >
        <Form
          {...formLayout}
          form={formBlbj}
        >
          <Row>
            <Col span={22}><FormItem
              name="companyName"
              label="投标单位"
            >
              <Input bordered={false} readOnly />
            </FormItem></Col>
          </Row>
          <Row>
            <Col span={22}><FormItem
              name="sectionName"
              label="标包"
            >
              <Input bordered={false} readOnly />
            </FormItem></Col>
          </Row>
          <Row>
            <Col span={22}><FormItem
              name="newPrice"
              label="报价(单位：元)"
              rules={[{
                required: true,
                message: '当前项不可为空！'
              }]}
            >
              <Input type='number' />
            </FormItem></Col>
          </Row>
          <Row>
            <Col span={22}><FormItem
              name="contentDataId"
              label="数据表id"
              hidden={true}
            >
              <Input />
            </FormItem></Col>
          </Row>
          <Row>
            <Col span={22}><FormItem
              name="tendererId"
              label="投标人id"
              hidden={true}
            >
              <Input />
            </FormItem></Col>
          </Row>
          <Row>
            <Col span={22}><FormItem
              name="remark"
              label="备注"
            >
              <TextArea />
            </FormItem></Col>
          </Row>
        </Form>
      </Modal>
    )
  }
  //解密进度
  const jmjd = () => {
    return (
      <Modal
        title="解密进度"
        width={'800px'}
        destroyOnClose
        centered
        bodyStyle={{ padding: '32px 40px 48px', overflowY: 'auto' }}
        visible={rateVis}
        footer={false}
        onCancel={() => { getTableData(); handleRateVis(false); }}
      >
        {/* <img src={timg} alt="" width='100%' height="75%" /> */}
        <Progress percent={Math.floor(jmComplete / jmFileCount) * 100} status="active" />

        <div style={{ textAlign: "center" }}>
          文件总数：<span style={{ fontSize: 30, color: 'rgb(0,144,255)' }}>{jmFileCount}</span> 个
        </div>
        <div style={{ textAlign: "center" }}>
          解密成功：<span style={{ fontSize: 30, color: 'rgb(61,169,92)' }}>{jmComplete}</span> 个,
          {/* 排队解密中：<span style={{ fontSize: 30, color: 'red' }}>{100 - rate}</span> 个, */}
          正在解密：<span style={{ fontSize: 30, color: 'rgb(0,144,255)' }}>{jmWait}</span> 个,
          解密失败：<span style={{ fontSize: 30, color: 'red' }}>{jmFail}</span> 个
        </div>
      </Modal>
    )
  }
  //分项报价表
  const [fxData, fxDataSet] = useState<any>([{}]);
  const [columnsFx, columnsFxSet] = useState<any>([]);
  async function queryFxbj(record: any,id:any) {
    // const [tendererId] = record;
    // queryFx({tendererId:tendererId,tdocId:tdocId,tdocCatalogId:'1319439263309234001'}).then(()=>{
    console.log(id);
    
    let columnfx: any = [];
    let fxData: any = [];
    await queryFx({ tendererId: record.tendererId, tdocId: id, tdocCatalogId: record.tdocCatalogId }).then((res) => {
      console.log(res);

      if (res.data != undefined) {
        //拼表格        
        columnfx.push({ title: '序号', dataIndex: 'index', valueType: 'index', });
        res.data.itemPriceTitle.map((item: any, index: any) => {
          columnfx.push({ title: item.name, dataIndex: item.id, key: index });
        });

        //拼数据
        let fxIndex = 0;
        const priD = res.data.itemPriceData;
        for (const key in priD) {
          let one = {};
          one["key"] = fxIndex;
          // console.log(priD[key]);
          for (const key2 in priD[key]) {
            one[`${key2}`] = priD[key][key2]['evaluatingContent'];
          }
          fxIndex = fxIndex + 1;
          fxData.push(one);
        }
        // console.log(fxData);
        fxDataSet(fxData);
      }

    });
    columnsFxSet(columnfx);

  }
  const fxbj = () => {
    return (
      <Modal
        title="分项报价表"
        width={'60%'}
        destroyOnClose
        bodyStyle={{ padding: '32px 40px 48px', overflowY: 'auto', height: '500px' }}
        visible={subentryVis}
        footer={false}
        onCancel={() => {handleSubentryVis(false);fxDataSet([])}}
      >
        <ProTable
          columns={columnsFx}//表格
          dataSource={fxData}
          search={false}
          size={'small'}
          rowSelection={false}
          options={false}
          // pagination={{ defaultPageSize: 10 }}//默认显示条数
          pagination={false}//默认显示条数
        />
      </Modal>
    )
  }

  //解密时限
  const jmTime = () => {
    return (
      <>
        <Modal
          title="设置解密时限"
          width={'400px'}
          destroyOnClose
          centered
          bodyStyle={{ overflowY: 'auto' }}
          visible={jmTimeVis}
          onCancel={() => { jmTimeVisSet(false); }}
          onOk={() => {
            endTimeConfig({ id: openRoom, opingTimeLimit: endTime });
            jmTimeVisSet(false);
          }}
        >
          要求供应商在开标后 <Input type='number' style={{ width: '80px' }} value={endTime} onChange={(event) => {
            endTimeSet(event.target.value);
          }} /> 分钟内完成解密操作
        </Modal>
      </>
    )
  }
  //未开标
  let height = document.body.clientHeight - 70;
  // function notOpen() {
  //   return (
  //     <div style={{ width: '100%', height: `${height}px`, paddingTop: `${0.4 * height}px`, backgroundColor: 'white', textAlign: 'center' }}>
  //       <div style={{}}>暂未开标</div>
  //     </div>
  //   )
  // }
  return (
    <>
      <div className={styles.header}>
        <div className={styles.headerAlign}>
          <span>电子开标室</span>
        </div>
      </div>
      <Spin spinning={spin} size='large'>
        <div style={{ width: '100%', height: `${height}px`, backgroundColor: 'white', }}>
          {
            openState ?
              <div>
                {/* 开标记录表 */}
                {kbjl()}
                {/* 补录报价 */}
                {blbj()}
                {/* 解密进度 */}
                {jmjd()}
                {/* 分项报价 */}
                {fxbj()}
                {/* 解密时限 */}
                {jmTime()}
              </div>
              : null
            // : <>{notOpen()}</>
          }
        </div>
      </Spin>
    </>
  )
};
export default Room;