import React, { useEffect, useState, useRef } from 'react';
import { Switch, Button, Message, Spin, Modal } from 'antd';
// import axios from 'axios';

import BaseForm from '@/components/BaseForm/index';
import { getApkNameAndDate, SaveMobileApk } from '@/services/appConfig/api';
import { getMobileFiles } from '@/services/mobileConfig/api';

import styles from './otherConfig.less';

// const JSON_BASE = `${
//   location.origin
// }/cityinterface/rest/services/filedownload.svc/download/BufFile/Mobile/APK/`;

export default props => {
  console.log(props);
  const { clientName } = props;
  const items = [
    {
      label: '更新描述',
      dataIndex: 'describe',
      rules: [
        {
          required: true,
          message: '请输入apk的更新描述',
        },
      ],
      formType: 'INPUT',
    },
    {
      label: '强制更新',
      dataIndex: 'forceUpdate',
      initialValue: 1,
      rules: [
        {
          required: true,
          message: '请选择是否强制更新',
        },
      ],
      options: [
        {
          children: '是',
          value: 1,
        },
        {
          children: '否',
          value: 0,
        },
      ],
      formType: 'SINGLE_RADIO',
    },
  ];

  const formEntity = useRef(null);
  const fileEntity = useRef(null);
  const [loading, setLoading] = useState(false); // 显示请求的loading
  const [showModal, setShowModal] = useState(false); // 显示更新的modal
  const [fileData, setFileData] = useState({}); // 获取到的包名和更新时间
  const [file, setFile] = useState({}); // 上传的文件
  const [fileSuccess, setFileSuccess] = useState(false); // 本地文件是否成功
  const [progress, setProgress] = useState(false); // 是否正在保存
  const [upFlag, setUpFlag] = useState(1);

  // const uploadProps = {
  //   name: 'file',
  //   action: `${window.location.origin}${PUBLISH_SERVICE}/FileCenter/UploadSingleFile`,
  //   headers: {
  //     Authorization: 'Bearer ' + localStorage.getItem('token') || '',
  //   },
  //   onChange(info) {
  //     console.log(info)
  //     setFile(info.file);
  //   },
  // };

  const submitForm = () => {
    console.log(formEntity);
    const { validateFields } = formEntity.current;
    validateFields()
      .then(values => {
        const { describe, forceUpdate } = values;
        const formData = new FormData();
        formData.set('description', describe);
        formData.set('isRefresh', !!forceUpdate);
        formData.set('file', file);
        formData.set('client', clientName);
        setProgress(true);
        SaveMobileApk(formData).then(res => {
          console.log(res);
          setProgress(false);
          if (Number(res.code) === 0) {
            Message.success('更新成功');
            setUpFlag(upFlag + 1);
            setShowModal(false);
            init();
          } else {
            // Message.error(res.msg);
          }
        });
      })
      .catch(res => {
        const { errorFields, values } = res;
        console.log(errorFields, values);
      });
  };

  const handleGetForm = form => {
    formEntity.current = form;
  };

  const handleFileChange = e => {
    console.log(e.target.files);
    setFile(e.target.files[0]);
    setFileSuccess(true);
  };

  const handleUpload = () => {
    fileEntity.current.click();
  };

  const init = () => {
    // getApkNameAndDate({})
    //   .then(res => {
    //     const message = res.ResultMessage || '';
    //     const [fileName = '', updateTime] = message.split(',');
    //     setFileData({
    //       fileName,
    //       updateTime,
    //     });
    //     setLoading(false);
    //     // const index = fileName.lastIndexOf('.');
    //     // axios
    //     //   .get(`${JSON_BASE}${fileName.slice(0, index)}.json`, {})
    //     //   .then(res => {
    //     //     console.log(res);
    //     //   });
    //   })
    //   .catch(err => {
    //     Message.error(err);
    //     setLoading(false);
    //   });
  };

  useEffect(() => {
    init();
  }, []);
  useEffect(() => {
    const hurl = window.location.origin;
    getMobileFiles({ client: clientName }).then(res => {
      if (res.code === 0) {
        const { data } = res;
        let fileName = data.apkPath.split('\\')[data.apkPath.split('\\').length - 1] || '';
        let apkUrl = `${hurl}/${data.apkPath.replace(/\\/g, '/')}` || '';
        setFileData({
          ...data,
          fileName,
          apkUrl,
        });
      }
    });
  }, [upFlag]);
  return (
    <div className={loading ? styles.loadingContainer : styles.VersionPublish}>
      {loading ? (
        <Spin />
      ) : (
        <>
          <div className={styles.apkbox}>
            <p className={styles.title}>apk版本管理：</p>
            <div className={styles.row}>
              <div className={styles.label}>当前包名：</div>
              <div className="value">{fileData.fileName || '未找到对应的包名'}</div>
            </div>
            <div className={styles.row}>
              <div className={styles.label}>更新时间：</div>
              <div className="value">{fileData.updateTime}</div>
            </div>
            <div className={styles.row}>
              <div className={styles.label}>下载地址：</div>
              <div className="value">
                <a href={fileData.apkUrl} target="_blank">
                  {fileData.apkUrl}
                </a>
              </div>
            </div>
            <div className={styles.row}>
              <div className={styles.label}>更新描述：</div>
              <div className="value">{fileData.description}</div>
            </div>
            <div className={styles.row}>
              <div className={styles.label}>强制更新：</div>
              <div className="value">
                <Switch checked={fileData.isRefresh} disabled />
              </div>
            </div>
            <Button
              style={{ marginLeft: '115px', marginTop: '20px' }}
              type="primary"
              onClick={() => setShowModal(true)}
            >
              更新
            </Button>
          </div>
        </>
      )}
      {showModal && (
        <Modal
          visible={showModal}
          closable={false}
          maskClosable={false}
          onCancel={() => setShowModal(false)}
          onOk={submitForm}
          confirmLoading={progress}
        >
          <Spin spinning={progress} tip="loading...">
            <BaseForm items={items} getForm={handleGetForm} />
            <div className={styles.row}>
              <div className={`${styles.label2} ${styles.required}`}>apk文件：</div>
              <input
                ref={f => {
                  fileEntity.current = f;
                }}
                className={styles['file-item']}
                type="file"
                onChange={handleFileChange}
              />
              <Button type="primary" onClick={handleUpload}>
                {fileSuccess ? '上传成功' : '开始上传'}
              </Button>
            </div>
          </Spin>
        </Modal>
      )}
    </div>
  );
};
