import { Modal, Input, Form } from '@easyv/antd';
import styles from './PersonalModal.less';
import classnames from 'classnames';
import saasPersonalIcon from 'images/saas_personal.svg';
import saasAdvancedIcon from 'images/saas_advanced.svg';
import otherRole from 'images/role_other.svg';
import personnelRole from 'images/role_personnel.svg';
import productManagerRole from 'images/role_product_manager.svg';
import projectManagerRole from 'images/role_project_manager.svg';
import redactRole from 'images/role_redact.svg';
import studentRole from 'images/role_student.svg';
import stylistRole from 'images/role_stylist.svg';
import technologyRole from 'images/role_technology.svg';
import { connect } from 'react-redux';
import { UserInfo } from 'models/user.types';
import React, { useState } from 'react';
import { RootState } from 'models';
import EasyvModal, { useActionModalRef } from './EasyvModal';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { updateVersionByName } from 'services/applyForTrial';

const FormItem = Form.Item;

const rolesList = [
  {
    key: 0,
    src: stylistRole,
    name: '设计师'
  },
  {
    key: 1,
    src: productManagerRole,
    name: '产品经理'
  },
  {
    key: 2,
    src: technologyRole,
    name: '技术研发'
  },
  {
    key: 3,
    src: projectManagerRole,
    name: '项目经理'
  },
  {
    key: 4,
    src: redactRole,
    name: '运营/编辑'
  },
  {
    key: 5,
    src: personnelRole,
    name: '财务/人事'
  },
  {
    key: 6,
    src: studentRole,
    name: '教师/学生'
  },
  {
    key: 7,
    src: otherRole,
    name: '其它'
  }
];

type VersionModalType = {
  visible: boolean;
  userInfo: UserInfo;
  changeVisible: (e: boolean) => void;
};

const PersonalModal = (props: VersionModalType) => {
  const [curIndex, setCurIndex] = useState(-1);
  const { visible, changeVisible } = props;
  const modaleRef = useActionModalRef();
  const peopelModaleRef = useActionModalRef();
  const [form] = Form.useForm();

  const { skuId, edition, tenantId } = props.userInfo;

  const expiredAt = edition?.expiredAt;
  const becomeTime = Math.floor((Date.parse(expiredAt) - Date.now()) / (1000 * 24 * 60 * 60));

  const update = () => {
    changeVisible(false);
    skuId === 7 ? modaleRef.current?.show() : peopelModaleRef.current?.show();
  };

  const submit = async () => {
    if (skuId === 7) {
      form
        .validateFields()
        .then(async () => {
          const data = form.getFieldsValue();
          const res = await updateVersionByName(tenantId, data);
          if (res) {
            modaleRef.current?.close();
            window.location.href = `${BASENAME || '/'}`;
          }
        })
        // eslint-disable-next-line @typescript-eslint/no-empty-function
        .catch(() => {});
    }
    if (skuId === 2) {
      const role = rolesList.filter((d) => d.key === curIndex);
      // eslint-disable-next-line no-prototype-builtins
      if (!(Array.prototype.isPrototypeOf(role) && role.length === 0)) {
        const res = await updateVersionByName(tenantId, {
          realName: '1',
          occupation: role[0].name
        });
        if (res) {
          peopelModaleRef.current?.close();
          window.location.href = `${BASENAME || '/'}`;
        }
      }
    }
  };

  return (
    <div className={classnames(styles.wrap, styles['black'])}>
      <Modal
        title="申请企业版试用"
        width={620}
        getContainer={false}
        onCancel={() => {
          changeVisible(false);
        }}
        visible={visible}
        footer={null}>
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <div className={styles.versionForm}>
            <div style={{ display: 'flex', justifyContent: 'space-around', alignItems: 'center' }}>
              <img
                style={{
                  marginLeft: '-4px',
                  lineHeight: '19px',
                  marginRight: 5
                }}
                src={saasPersonalIcon}
                alt=""
              />
              <span style={{ fontSize: '18px', fontWeight: 600, color: '#fff' }}>个人版</span>
            </div>
            <span className={styles.introduce}>零代码上手标准数字看板搭建</span>
            <ul className={styles.versionUl}>
              <li>
                <span>个人使用</span>
              </li>
              <li>
                <span>各类优质主题模板</span>
              </li>
              <li>
                <span>在线表格一键接入</span>
              </li>
            </ul>
            {skuId === 7 ? (
              <span className={styles.become}>剩余{becomeTime}天试用</span>
            ) : (
              <span className={styles.probation} onClick={update}>
                免费试用
              </span>
            )}
          </div>

          <div className={styles.versionForm}>
            <div style={{ display: 'flex', justifyContent: 'space-around', alignItems: 'center' }}>
              <img
                style={{
                  marginLeft: '-4px',
                  lineHeight: '19px',
                  marginRight: 5
                }}
                src={saasAdvancedIcon}
                alt=""
              />
              <span style={{ fontSize: '18px', fontWeight: 600, color: '#fff' }}>企业高级版</span>
            </div>

            <span className={styles.introduce}>低代码企业数字驾驶舱协同搭建</span>
            <ul className={styles.versionUl}>
              <li>
                <span>企业使用</span>
              </li>
              <li>
                <span>多空间协同搭建</span>
              </li>
              <li>
                <span>主流数据源实时接入</span>
              </li>
            </ul>
            {skuId === 2 ? (
              <span className={styles.become}>剩余{becomeTime}天试用</span>
            ) : (
              <span className={styles.probation} onClick={update}>
                免费试用
              </span>
            )}
          </div>
        </div>
      </Modal>

      <EasyvModal.ActionModal
        ref={modaleRef}
        title="申请企业版试用"
        width={468}
        className={styles.modaleContiner}
        content={
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            <span style={{ color: '#fff', marginBottom: '12px' }}>企业名称</span>
            <Form form={form}>
              <FormItem
                name="companyName"
                rules={[
                  { required: true, message: '请输入企业名称' },
                  { max: 45, message: '名称过长' }
                ]}>
                {<Input type="text" placeholder="请输入您的企业名称" />}
              </FormItem>
            </Form>
            <div style={{ color: '#757881', marginTop: '14px', marginBottom: '44px' }}>
              <ExclamationCircleOutlined />
              <span style={{ paddingLeft: '5px', fontSize: '12px' }}>版本切换后不支持切回版本，请谨慎操作，如有存疑请联系在线客服</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <a href={`${window.appConfig.HOME_URL}/price`} target="_blank">
                <span className={classnames(styles.btn, styles.lookBtn)}>查看版本对比</span>
              </a>
              <span className={classnames(styles.btn, styles.openBtn)} onClick={submit}>
                开启企业高级版
              </span>
            </div>
          </div>
        }
        footer={null}
      />
      <EasyvModal.ActionModal
        ref={peopelModaleRef}
        width={620}
        className={styles.modaleContiner}
        title="申请个人版试用"
        content={
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            <span style={{ color: '#fff', marginTop: '8px' }}>您的角色是？</span>
            <ul className={styles.role}>
              {rolesList.map((item) => (
                <li
                  key={item.key}
                  onClick={() => setCurIndex(item.key)}
                  className={classnames(styles.roleList, curIndex === item.key ? styles.active : null)}>
                  <img src={item.src} alt="" style={{ marginBottom: '1px' }} />
                  <span style={{ fontSize: '12px' }}>{item.name}</span>
                </li>
              ))}
            </ul>
            <div style={{ color: '#757881', marginTop: '6px', marginBottom: '44px' }}>
              <ExclamationCircleOutlined />
              <span style={{ paddingLeft: '5px', fontSize: '12px' }}>版本切换后不支持切回版本，请谨慎操作，如有存疑请联系在线客服</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <a href={`${window.appConfig.HOME_URL}/price`} target="_blank">
                <span className={classnames(styles.btn, styles.lookBtn)} style={{ width: '282px' }}>
                  查看版本对比
                </span>
              </a>
              <span
                className={classnames(styles.btn, styles.openBtn, curIndex == -1 && styles.prohibit)}
                style={{ width: '282px' }}
                onClick={submit}>
                开启个人版
              </span>
            </div>
          </div>
        }
        footer={null}
      />
    </div>
  );
};

function mapStateToProps(state: RootState) {
  const { user } = state;
  const { userInfo } = user;
  return {
    userInfo
  };
}

export default connect(mapStateToProps)(PersonalModal);
