import { getNodeResult, getQueryByExperimentLog } from '@/services/experiment/index.js';
import { elapsedTime } from '@/utils/date';
import { downLoadZip } from '@/utils/downloadfile';
import { DatabaseOutlined, ProfileOutlined } from '@ant-design/icons';
import { Drawer, Form, Input, Tabs, message } from 'antd';
import moment from 'moment';
import { forwardRef, useImperativeHandle, useState } from 'react';
import LogList from './LogList';
import Styles from './editPipeline.less';
const { TextArea } = Input;
const Props = forwardRef(({ onParentChange }, ref) => {
  const [form] = Form.useForm();
  const [stagingItem, setStagingItem] = useState({});
  const [resultObj, setResultObj] = useState([]);
  const [logList, setLogList] = useState([]);
  const statusObj = {
    Running: '运行中',
    Succeeded: '成功',
    Pending: '等待中',
    Failed: '失败',
    Error: '错误',
    Terminated: '终止',
    Skipped: '未执行',
    Omitted: '未执行',
  };
  const statusColorObj = {
    Running: '#165bff',
    Succeeded: '#63a728',
    Pending: '#f981eb',
    Failed: '#c73131',
    Error: '#c73131',
    Terminated: '#8a8a8a',
    Skipped: '#8a8a8a',
    Omitted: '#8a8a8ae',
  };
  const exportResult = (e, val) => {
    const hide = message.loading('正在下载');
    hide();
    downLoadZip(`/api/mmp/minioStorage/download`, { path: val });
  };
  const timers = (time) => {
    let timer = new Date(time);
    let hours = timer.getHours(); //转换成时
    let minutes = timer.getMinutes(); //转换成分
    let secend = timer.getSeconds(); //转换成秒

    let str = `${minutes}分${secend}秒`;
    return str;
  };
  const items = [
    {
      key: '1',
      label: '日志详情',
      children: <LogList list={logList} status={stagingItem.experimentStatus}></LogList>,
      icon: <ProfileOutlined />,
    },
    {
      key: '2',
      label: '配置参数',
      icon: <DatabaseOutlined />,
      children: (
        <Form
          name="form"
          form={form}
          layout="vertical"
          labelCol={{
            span: 16,
          }}
          wrapperCol={{
            span: 16,
          }}
          style={{
            maxWidth: 600,
          }}
          initialValues={{
            remember: true,
          }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <div className={Styles.editPipelinePropsContent}>
            <img
              style={{ width: '13px', marginRight: '10px' }}
              src={'/assets/images/static-message.png'}
              alt=""
            />
            基本信息
          </div>
          <Form.Item
            label="任务名称"
            name="label"
            rules={[
              {
                required: true,
                message: '请输入任务名称',
              },
            ]}
          >
            <Input disabled />
          </Form.Item>
          <Form.Item
            label="任务ID"
            name="id"
            rules={[
              {
                required: true,
                message: '请输入任务id',
              },
            ]}
          >
            <Input disabled />
          </Form.Item>
          <div className={Styles.editPipelinePropsContent}>
            <img
              style={{ width: '13px', marginRight: '10px' }}
              src={'/assets/images/duty-message.png'}
              alt=""
            />
            任务信息
          </div>
          <Form.Item
            label="镜像"
            name="image"
            rules={[
              {
                required: true,
                message: '请输入镜像',
              },
            ]}
          >
            <Input disabled />
          </Form.Item>
          <Form.Item label="工作目录" name="working_directory">
            <Input disabled />
          </Form.Item>

          <Form.Item label="启动命令" name="command">
            <Input disabled />
          </Form.Item>
          <Form.Item
            label="资源规格"
            name="resources_standard"
            rules={[
              {
                required: true,
                message: '请输入资源规格',
              },
            ]}
          >
            <Input disabled />
          </Form.Item>
          <Form.Item label="挂载路径" name="mount_path">
            <Input disabled />
          </Form.Item>
          <Form.Item label="环境变量" name="env_variables">
            <TextArea disabled />
          </Form.Item>
          {stagingItem.control_strategy &&
          Object.keys(stagingItem.control_strategy) &&
          Object.keys(stagingItem.control_strategy).length > 0
            ? Object.keys(stagingItem.control_strategy).map((item) => (
                <Form.Item label={stagingItem.control_strategy[item].label} disabled name={item}>
                  <Input disabled />
                </Form.Item>
              ))
            : ''}
          <div className={Styles.editPipelinePropsContent}>
            <img
              style={{ width: '13px', marginRight: '10px' }}
              src={'/assets/images/duty-message.png'}
              alt=""
            />
            输入参数
          </div>
          {stagingItem.in_parameters &&
          Object.keys(stagingItem.in_parameters) &&
          Object.keys(stagingItem.in_parameters).length > 0
            ? Object.keys(stagingItem.in_parameters).map((item) => (
                <Form.Item
                  label={stagingItem.in_parameters[item].label + '(' + item + ')'}
                  name={item}
                  disabled
                  rules={[{ required: stagingItem.in_parameters[item].require ? true : false }]}
                >
                  <Input disabled />
                </Form.Item>
              ))
            : ''}
          <div className={Styles.editPipelinePropsContent}>
            <img
              style={{ width: '13px', marginRight: '10px' }}
              src={'/assets/images/duty-message.png'}
              alt=""
            />
            输出参数
          </div>
          {stagingItem.out_parameters &&
          Object.keys(stagingItem.out_parameters) &&
          Object.keys(stagingItem.out_parameters).length > 0
            ? Object.keys(stagingItem.out_parameters).map((item) => (
                <Form.Item
                  label={stagingItem.out_parameters[item].label + '(' + item + ')'}
                  disabled
                  rules={[{ required: stagingItem.out_parameters[item].require ? true : false }]}
                  name={item}
                >
                  <Input disabled />
                </Form.Item>
              ))
            : ''}
        </Form>
      ),
    },
    {
      key: '3',
      label: '输出结果',
      children: (
        <div
          style={{
            minHeight: '740px',
            background: '#f4f4f4',
            color: '#000',
            fontSize: '14px',
            padding: '0 10px 20px 20px',
          }}
        >
          {resultObj && resultObj.length > 0
            ? resultObj.map((item) => (
                <div>
                  <div className={Styles.resultTop}>
                    <span>{item.name}</span>
                    <div style={{ display: 'flex' }}>
                      <a
                        onClick={(e) => {
                          exportResult(e, item.path);
                        }}
                        style={{ marginRight: '10px' }}
                      >
                        下载
                      </a>
                      <a style={{ marginRight: '10px' }}>导出到模型库</a>
                      <a style={{ marginRight: '10px' }}>导出到数据集</a>
                    </div>
                  </div>
                  <div style={{ margin: '15px 0' }} className={Styles.resultContent}>
                    <span>文件名称</span>
                    <span>文件大小</span>
                  </div>
                  {item.value && item.value.length > 0
                    ? item.value.map((ele) => (
                        <div className={Styles.resultContent}>
                          <span>{ele.name}</span>
                          <span>{ele.size}</span>
                        </div>
                      ))
                    : null}
                </div>
              ))
            : null}
        </div>
      ),
      icon: <ProfileOutlined />,
    },
  ];
  const [open, setOpen] = useState(false);
  const afterOpenChange = () => {
    if (!open) {
      console.log(111, open);

      console.log(stagingItem, form.getFieldsValue());
      for (let i in form.getFieldsValue()) {
        for (let j in stagingItem.in_parameters) {
          if (i == j) {
            console.log(j, i);
            stagingItem.in_parameters[j].value = form.getFieldsValue()[i];
          }
        }
        for (let p in stagingItem.out_parameters) {
          if (i == p) {
            stagingItem.out_parameters[p].value = form.getFieldsValue()[i];
          }
        }
        for (let k in stagingItem.control_strategy) {
          if (i == k) {
            stagingItem.control_strategy[k].value = form.getFieldsValue()[i];
          }
        }
      }
      // setStagingItem({...stagingItem,})
      console.log(stagingItem.control_strategy);
      onParentChange({
        ...stagingItem,
        control_strategy: JSON.stringify(stagingItem.control_strategy),
        in_parameters: JSON.stringify(stagingItem.in_parameters),
        out_parameters: JSON.stringify(stagingItem.out_parameters),
        ...form.getFieldsValue(),
      });
      // onParentChange({...stagingItem,...form.getFieldsValue()})
    }
  };
  const onClose = () => {
    setOpen(false);
  };
  const onFinish = (values) => {
    console.log('Success:', values);
  };
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  useImperativeHandle(ref, () => ({
    showDrawer(e, id, message) {
      setLogList([]);
      if (e.item && e.item.getModel().component_id) {
        const model = e.item.getModel() || {};
        const start_time = moment(model.experimentStartTime).valueOf() * 1.0e6;
        const params = {
          task_id: model.id,
          component_id: model.component_id,
          name: message.argo_ins_name,
          namespace: message.argo_ins_ns,
          start_time: start_time,
        };
        getQueryByExperimentLog(params).then((ret) => {
          const { log_type, pods, log_detail } = ret.data;
          if (log_type === 'normal') {
            const list = [
              {
                ...log_detail,
                log_type,
              },
            ];
            setLogList(list);
          } else if (log_type === 'resource') {
            const list = pods.map((v) => ({
              log_type,
              pod_name: v,
              log_content: '',
              start_time,
            }));
            setLogList(list);
          }

          getNodeResult({ id, node_id: e.item.getModel().id }).then((res) => {
            setResultObj(res.data);
            form.resetFields();
            form.setFieldsValue({
              ...e.item.getModel(),
              in_parameters: JSON.parse(e.item.getModel().in_parameters),
              out_parameters: JSON.parse(e.item.getModel().out_parameters),
              control_strategy: JSON.parse(e.item.getModel().control_strategy),
            });
            setStagingItem({
              ...e.item.getModel(),
              in_parameters: JSON.parse(e.item.getModel().in_parameters),
              out_parameters: JSON.parse(e.item.getModel().out_parameters),
              control_strategy: JSON.parse(e.item.getModel().control_strategy),
            });
            setOpen(true);
          });
        });
      } else {
        form.resetFields();
        form.setFieldsValue({
          ...e.item.getModel(),
          in_parameters: JSON.parse(e.item.getModel().in_parameters),
          out_parameters: JSON.parse(e.item.getModel().out_parameters),
          control_strategy: JSON.parse(e.item.getModel().control_strategy),
        });
        setStagingItem({
          ...e.item.getModel(),
          in_parameters: JSON.parse(e.item.getModel().in_parameters),
          out_parameters: JSON.parse(e.item.getModel().out_parameters),
          control_strategy: JSON.parse(e.item.getModel().control_strategy),
        });
        setOpen(true);
      }
      // console.log(e.item.getModel().in_parameters);
    },
  }));
  return (
    <>
      <Drawer
        title="任务执行详情"
        placement="right"
        closeIcon={false}
        onClose={onClose}
        afterOpenChange={afterOpenChange}
        open={open}
        width={600}
        destroyOnClose={true}
      >
        <div className={Styles.detailBox}>任务名称：{stagingItem.label}</div>
        <div className={Styles.detailBox}>
          执行状态：
          <div
            style={{
              width: '8px',
              height: '8px',
              borderRadius: '50%',
              marginRight: '6px',
              backgroundColor: statusColorObj[stagingItem.experimentStatus],
            }}
          ></div>
          <span style={{ color: statusColorObj[stagingItem.experimentStatus] }}>
            {statusObj[stagingItem.experimentStatus]}
          </span>
        </div>
        <div className={Styles.detailBox}>
          启动时间：{moment(stagingItem.experimentStartTime).format('YYYY-MM-DD HH:mm:ss')}
        </div>
        <div className={Styles.detailBox}>
          耗时：
          {stagingItem.experimentEndTime
            ? elapsedTime(
                new Date(stagingItem.experimentStartTime),
                new Date(stagingItem.experimentEndTime),
              )
            : elapsedTime(new Date(stagingItem.experimentStartTime), new Date())}
        </div>
        <Tabs defaultActiveKey="1" items={items} />
      </Drawer>
    </>
  );
});

export default Props;
