import React, { useEffect, useState } from 'react';
import { Form, Input, Modal, Spin, Skeleton } from 'antd';
import {
  fetchJuryMemInfo,
  getCheckedByRoomId,
  updateJuryMemInfo,
  validateVerificationCode,
} from '@/services/bidev';
import ExpertCommitment from './ExpertCommitment';
import { getProId, getProMethod } from '@/utils/session';
import { getDefId } from './service';

interface ExpertEnterProps {
  //专家角色行数据传入
  recordData?: any;
  //展开关闭状态
  modalVisible?: boolean;
  //退出
  onCancel: () => void;
  //刷新方法
  onRefresh: () => void;
}

const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 13 },
};

const validateMessages = {
  required: '请填写${label}',
};

const ExpertEnter: React.FC<ExpertEnterProps> = (props) => {
  const { recordData, modalVisible, onCancel , onRefresh } = props;
  const FormItem = Form.Item;
  const [form] = Form.useForm();
  //获取采购方式
  const proMethod: any = getProMethod();
  //判断是否是第一次进入系统参数
  const [display, setDisplay] = useState<boolean>(false);
  //显示专家承诺书
  const [commitVisible, setCommitVisible] = useState<boolean>(false);
  //专家信息存储
  // const [JuryInfo, setJuryInfo] = useState<any>('');
  //初始化显示字段
  const [sectionType, setSectionType] = useState<any>('评审');
  //loading
  const [spin, spinSet] = useState<boolean>(false);
  //Skeleton loading
  const [skeletonLoading, setSkeletonLoading] = useState<boolean>(false);
  //提交表单
  const onOk = () => {
    form.submit();
  };
  // 校验验证码及修改用户信息
  const onFinish = async (formData: any) => {
    spinSet(true);
    const params = {
      name: formData.name,
      mobile: formData.mobile,
      id: formData.id,
    };
    const paramst = {
      id: recordData?.id,
      verificationCode: formData.verificationCode,
    };
    //保存评委数据
    await updateJuryMemInfo(params);
    //校验验证码
    await validateVerificationCode(paramst).then((res) => {
      if (res?.code == 200 && res?.data == true) {
        onCancel();
        if (display == true) {
          //获取流程id
          getDefId(getProId()).then(res => {
            if(res?.code == 200) {
              sessionStorage.setItem('defId', JSON.stringify(res?.data));
              window.open('/EvaRoom');
            }
          })
        } else {
          //打开专家承诺书界面
          setCommitVisible(true);
        }
      }
    }).finally(() => {
      spinSet(false);
    });
  };

  useEffect(() => {
    if (modalVisible) {
      //修改显示字段
      if (proMethod == 'procurement_mode_1' || proMethod == 'procurement_mode_2') {
        setSectionType('评标');
      } else if (proMethod == 'procurement_mode_5' || proMethod == 'procurement_mode_6') {
        setSectionType('谈判');
      }
      setSkeletonLoading(true)

      if (recordData == undefined) {
      } else {
        getInfo();
      }
    }
  }, [recordData?.id, modalVisible]);

  //获取数据
  const getInfo = async() => {
    const params = {
      roomId: recordData?.id,
    };
    const roomId = {
      assessRoomId: recordData?.id,
    };
    //获取承诺书状态
    await getCheckedByRoomId(roomId).then((res) => {
      if (res?.code == 200) {
        setDisplay(!res?.data);
        //获取专家数据
        fetchJuryMemInfo(params).then((response) => {
          if (response?.code == 200) {
            const data = response.data;
            // setJuryInfo(data);
            form.setFieldsValue({
              id: data?.id,
              name: data?.name,
              mobile: data?.mobile,
              certificate: data?.certificate,
            });
          }
        });
      }
    }).finally(() => {
      setSkeletonLoading(false)
    });
  }
  return (
    <>
      <Modal
        destroyOnClose
        cancelText="取消"
        okText="确定"
        onCancel={onCancel}
        onOk={onOk}
        confirmLoading={spin || skeletonLoading}
        visible={modalVisible}
        width={600}
        centered
      >
        <Spin spinning={spin} delay={300} tip="校验中，请稍等···">
        <Skeleton loading={skeletonLoading} active>
          <Form
            form={form}
            {...formItemLayout}
            preserve={false}
            onFinish={onFinish}
            validateMessages={validateMessages}
          >
            <h3 className="first-title">专家信息确认</h3>
            <FormItem label="姓名" name="name" rules={[{ required: !display }]}>
              <Input placeholder="请输入姓名" readOnly={display} bordered={!display} />
            </FormItem>
            <FormItem
              label="电话"
              name="mobile"
              rules={[
                { required: !display },
                {
                  pattern: /(^[1][3,4,5,6,7,8,9][0-9]{9}$)|(^(([0\+]\d{2,3}-)?(0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$)/,
                  message: '输入的电话号码不正确',
                },
              ]}
            >
              <Input placeholder="请输入电话" readOnly={display} bordered={!display} />
            </FormItem>
            <FormItem label="身份证号" name="certificate">
              <Input readOnly bordered={false} />
            </FormItem>
            <h3 className="first-title">{sectionType}室校验码</h3>
            <FormItem
              label="校验码"
              name="verificationCode"
              rules={[
                { required: true },
                {
                  pattern: /^[0-9]\d*$/,
                  message: '校验码必须是数字',
                },
              ]}
            >
              <Input placeholder="请输入校验码" maxLength={6} />
            </FormItem>
            <FormItem label="" name="id" hidden>
              <Input />
            </FormItem>
          </Form>
          </Skeleton>
        </Spin>
      </Modal>
      <ExpertCommitment
        modalVisible={commitVisible}
        onCancel={() => setCommitVisible(false)}
        recordData={recordData}
        onRefresh={onRefresh}
      />
    </>
  );
};

export default ExpertEnter;
