import React, { useState, useEffect } from 'react';
import { Input, Menu, Dropdown, Button, Icon, message, Table, Divider, Tag, Select, Form, Alert } from 'antd';
import { FormattedMessage } from 'umi-plugin-react/locale';
import channels from '../channel/channelList.less';
import MiniappIconSelect from '../../components/SelectButton/MiniappIconSelect'
import XForm, { FieldTypes } from '../../components/XForm';
import Wangedit from '../../components/Wangedit/Wangedit'
import router from 'umi/router';
import apis from '../../services/apis';
import request from '../../utils/request'

const { TextArea } = Input;
const { Option } = Select;

const header = props => {
  const goodsId = props.location.query.goodsId
  const [ goodsData, setGoodsData ] = useState({})
  if(goodsId){
    useEffect(() => {
      getGoodsData(goodsId);
    },[])

  // 查询列表
  const getGoodsData = (goodsId) => {
    request({ ...apis.integralMall.taGoods, urlData: { id: goodsId },}).then((data) => {
        console.log(data)
        setGoodsData(data)
    })
  }
  }

  const fields = [
    {
      label: '请选择首页功能',
      name: 'iconCode',
      render: <MiniappIconSelect />,
      value: goodsData.iconCode,
      rules: [
        {required: true, message: '请选择所属项目'},
      ]
    },
    {
      label: '功能名称',
      name: 'iconName',
      type: FieldTypes.Text,
      value: goodsData.iconName ,
      help: '不填就使用默认名称',
    },
    {
      label: '权重',
      name: 'sort',
      type: FieldTypes.Number,
      render: <Input type="number" style={{ width: 80}} />,
      value: goodsData.sort,
      rules: [
        { required: true, message: '请输入权重' },
      ],
      help: '数字越大越靠前',
    },
  ]

  const handleSubmit = values => {
    if (values.inventory > values.totalNum) {
      message.error('商品剩余数量不能大于商品总数量')
      return
  }

    if (goodsId) {
      values.goodsId = goodsId
      request({ ...apis.integralMall.updateTaGoods, data: values,}).then((data) => {
        cancelPage()
      }).catch((err) => {
        message.info(err.msg || err.message)
      })
      }else{
      request({ ...apis.integralMall.addTaGoods, data: values,}).then((data) => {
        cancelPage()
      }).catch((err) => {
        message.info(err.msg || err.message)
      })
      }
  }

  const cancelPage = () => {
    router.push({
      pathname: '/integralMall/GoodsList',
    });
  }

  return (
    <XForm onSubmit={handleSubmit} onCancel={cancelPage} fields={fields}></XForm>
  )
}

const WrappedNormalLoginForm = Form.create({ name: 'header' })(header);
export default WrappedNormalLoginForm
