import React, {forwardRef, useState, useEffect} from "react";
import { Button, Checkbox, Form, Input, message, Select } from "antd";
import { Link } from "react-router-dom";
import './index.scss';
import MdEditor from "../../../../../../modules/tpm/challengesnew/tpm-md-editor";
import { marketBot, getAllBotCategory, getMarketBotById, updateMarketBot } from "../../../../../../softbot/api";
import moment from "moment";
const {Option} = Select;

function Putaway(props){
  const {form, current_user, match:{params:{id}}, botDetail, location:{pathname}} = props;
  const { getFieldDecorator, validateFields , setFieldsValue } = form;
  const [ resource, setResource] = useState([]);
  const [ resourceFirst, setResourceFirst] = useState([]);
  const [ resourceSecond, setResourceSecond] = useState([]);
  const [ content , setContent ] = useState(undefined);
  const [ disabled , setDisabled ] = useState(undefined);
  const [ detail, setDetail] = useState(undefined);
  const [ isEdit, setIsEdit] = useState(undefined);

  useEffect(()=>{
    // 获取分类列表
    getAllBotCategory().then(res=>{
      if(res && res.code === 200){
        setResource(res.data.category_list);
        setResourceFirst(res.data.category_list);
        setResourceSecond(res.data.category_list);
      }
    })
    if(pathname && pathname.endsWith("/putaway/edit")){
      setIsEdit(true);
      setDisabled(true);
      getMarketBotById({bot_id: id}).then(res=>{
        if(res && res.code === 200){
          setDetail({
            ...res.data
          });
          setContent(res.data.market_intro);
        }
      })
    }else{
      setIsEdit(false);
      if(botDetail){
        const {bot_des, bot_name, webhook} = botDetail;
        setDetail({
          bot_id: id,
          category: "",
          first_func: undefined,
          logo: "",
          market_desc: undefined,
          market_name: bot_name,
          market_time: undefined,
          second_func: undefined,
          webhook: webhook
        })
        setContent(bot_des);
      }
    }
  }, [pathname, botDetail])

  // 监听同意协议
  function onChange(e){
    setDisabled(e.target.checked);
  }

  function onContentChange(value){
    setContent(value);
  };

  // 注册新的bot
  function submit(e){
    e.preventDefault();
    validateFields((err, fieldsValue)=>{
      if(err){
        return;
      }
      const {logo} = botDetail;
      if(isEdit){
        // 更改bot上架信息
        updateMarketBot({
          ...fieldsValue,
          category: "",
          is_receive_ag1: 1,
          is_receive_ag2: 0,
          logo: logo,
          market_time: "",
          login: current_user && current_user.login,
          user_id: current_user && current_user.user_id,
          bot_id: parseInt(id),
        }).then(res=>{
          if(res && res.code === 200){
            message.success("修改成功");
          }else{
            message.error(res.data);
          }
        })
      }else{
        // 上架bot
        marketBot({
          ...fieldsValue,
          login: current_user && current_user.login,
          user_id: current_user && current_user.user_id,
          bot_id: parseInt(id),
          category: "",
          is_receive_ag1: disabled ? 1 : 0,
          is_receive_ag2: 0,
          logo: logo,
          market_time: "",
        }).then(res=>{
          if(res && res.code === -1){
            message.error(res.data);
          }else{
            message.success("成功上架市场");
            props.history.push('/softbot/'+id);
          }
        })
      }
    })
  }

  return <div className="putawayBox">
    <div className="putaHead pb10 font-18 mb5">
      <a href="#" className="font-16">高级选项&gt;</a><b>上架Bot市场</b>
    </div>
    {detail && <Form className="putawayForm" onSubmit={submit}>
      <Form.Item label="上架Bot市场名称" className="width50 oneItem">
        {getFieldDecorator("market_name",{
          rules:[{required:true,message:"请输入上架Bot市场名称"}],
          initialValue: detail.market_name
        })(
          <Input.TextArea placeholder="请输入上架Bot市场名称" maxLength={50} className="height36" autoSize={true}/>
        )}
      </Form.Item>
      <Form.Item label="简要介绍" className="oneItem">
        {getFieldDecorator("market_desc",{
          rules:[{required:true,message:"请输入简要介绍"}],
          initialValue: detail.market_desc
        })(
          <Input.TextArea placeholder="请输入简要介绍的内容" maxLength={200} className="height36" autoSize={true}/>
        )}
      </Form.Item>
      <div className="selectBox">
        <Form.Item label="主要功能" className="selectOne oneItem">
          {getFieldDecorator("first_func",{
            rules:[{required:true,message:"请选择主要功能"}],
            initialValue: detail.first_func
          })(
            <Select placeholder="请选择" onChange={(value)=>{setResourceSecond(resource.filter(item => item !== value))}}>
              {resourceFirst.map(item=>{return <Option value={item} key={item}>{item}</Option>})}
            </Select>
          )}
        </Form.Item>
        <Form.Item label="次要功能" className="selectOne oneItem">
          {getFieldDecorator("second_func",{
            initialValue: detail.second_func
          })(
            <Select placeholder="请选择" onChange={(value)=>{setResourceFirst(resource.filter(item => item !== value))}}>
              {resourceSecond.map(item=>{return <Option value={item} key={item}>{item}</Option>})}
            </Select>
          )}
        </Form.Item>
      </div>
      <Form.Item label="详细介绍" className="oneItem introduce">
        {getFieldDecorator("market_intro",{
          rules:[{required:true,message:"请输入详细介绍"}],
          initialValue: content
        })(
          <MdEditor
            placeholder={"请输入详细介绍"}
            height={500}
            mdID={"order-new-description"}
            initValue={content}
            onChange={onContentChange}
            className="mt20"
            imageExpand={false}
          ></MdEditor>
        )}
      </Form.Item>
      {/* 此webhook用于bot上架之后，接收bot安装者的操作记录，由于此功能未上线，所以暂时屏蔽编辑入口 */}
      {/* <Form.Item label="订阅接收Webhook地址" className="width50 oneItem">
        {getFieldDecorator("webhook",{
          rules:[{required:true,message:"请输入Webhook地址"}],
          initialValue: detail.webhook
        })(
          <Input.TextArea placeholder="请输入Webhook地址" maxLength={200} className="height36" autoSize={true}/>
        )}
      </Form.Item> */}
      {!isEdit && <Form.Item>
        <Checkbox onChange={onChange}>我已阅读并接受<a className="login-form-forgot" href="https://forum.trustie.net/forums/5029/detail" target="_blank">《GitLink服务协议条款》</a></Checkbox>
      </Form.Item>}
      <Form.Item><Button style={{width:"129px", height: '36px'}} type="primary" htmlType="submit" disabled={!disabled} className="putawayBut mt20">{isEdit ? '保存修改' : '申请上架'}</Button></Form.Item>
    </Form>}
  </div>
}
export default Form.create()(forwardRef(Putaway));