import React, { useState, useEffect } from 'react';
import { Button, Row, Col, Input, InputNumber, Modal, notification, Select, Tooltip } from 'antd';
import createForm from '@zjxpcyc/xrc-form2';
import Style from '../style.less';
import { fetch, apis } from '../../../utils/request';

const XForm = createForm();
const saveMiniapp = fetch(apis.member.miniapp.edit);
const checkMiniapp = fetch(apis.member.miniapp.check);

const getEventValue = e => {
  return Object.prototype.hasOwnProperty.call(e, 'checked') ?
    e.checked : (e.target ? e.target.value : e)
}

const TplItem = React.forwardRef((props, ref) => {
  const [val, setVal] = useState(props.value)
  const [isSubs, setIsSubs] = useState(props.value.isSubscribe)

  const handleChange = field => e => {
    const fv = getEventValue(e);
    const newVal = { ...val, [`${field}`]: fv }
    setVal(newVal)

    if (field === 'isSubscribe') {
      setIsSubs(fv)
    }

    if (typeof props.onChange === 'function') {
      props.onChange(newVal)
    }
  }

  return (
    <div ref={ref}>
      <Input.Group compact>
        <Tooltip title="消息类型">
          <Select style={{ width: '15%' }} value={!!val.isSubscribe - 0} onChange={handleChange('isSubscribe')}>
            <Select.Option value={1}>订阅</Select.Option>
            <Select.Option value={0}>服务</Select.Option>
          </Select>
        </Tooltip>
        <Tooltip title="消息模板ID">
          <Input style={{ width: '45%' }} value={val.tplId} placeholder="消息模板ID" onChange={handleChange('tplId')}></Input>
        </Tooltip>
        {
          !isSubs ?
            (<Tooltip title="消息字段数, 最大 100"><InputNumber min={0} max={100} style={{ width: '40%' }} value={val.fieldNum} placeholder="字段数" onChange={handleChange('fieldNum')}></InputNumber></Tooltip>) :
            (<Tooltip title="消息字段, 多字段用 | 分隔"><Input style={{ width: '40%' }} value={val.tplFields} placeholder="字段内容" onChange={handleChange('tplFields')}></Input></Tooltip>)
        }
      </Input.Group>
    </div>
  );
});

const Miniapp = (props) => {
  const [ visible, changeVisible ] = useState(false);
  const [ path, changePath ] = useState('/pages/project/index');
  const [ qrCode, setQrCode ] = useState();

  const user = props.data || {}
  const appdata = user.miniapp || {};
  const tpls = appdata.tpls || [];

  useEffect(() => {
    setQrCode(appdata.qrCode)
  }, [])

  const showModal = () => {
    changeVisible(true);
  }

  let form = undefined;
  const handleForm = f => {
    if (f) {
      form = f.props.form
    }
  }

  const handleModalOk = () => {
    const values = form.getFieldsValue()
    const data = { ...values, path }

    checkMiniapp({ data }).then(dt => {
      setQrCode(dt.qrCode)
      changeVisible(false)
      notification.success({ message: '校验成功' });
    }).catch();
  }

  const tplFields = (props.tplTyps || []).map((x) => {
    // console.log(props.tplTyps)
    // console.log('tpls: ', tpls)
    // console.log('appdata: ', appdata)
    // console.log('tpls.filter: ', tpls.filter(y => y.tplType === x.code)[0] || {})
    return {
      label: x.name,
      name: `tpl.${x.code}`,
      node: TplItem,
      value: tpls.filter(y => y.tplType === x.code)[0] || {},
      hidden: ({ allFieldsValues }) => allFieldsValues.isSubscribe,
    }
  })

  const fields = [
    {
      label: '名称',
      name: 'name',
      node: Input,
      value: appdata.name,
      rules: [{required: true, message: '请填写小程序名称'}]
    },
    {
      label: 'APPID',
      name: 'miniappId',
      node: Input,
      value: appdata.miniappId,
      props: {
        disabled: !!appdata.miniappId,
      },
      rules: [
        { required: true, message: '请填写 APPID' },
        { pattern: /^[a-zA-Z0-9]+$/, message: 'APPID 只能由字母与数字组成' }
      ]
    },
    {
      label: 'Secret',
      name: 'secret',
      node: Input,
      value: appdata.secret,
      rules: [
        { required: true, message: '请填写 Secret' },
        { pattern: /^[a-zA-Z0-9]+$/, message: 'APPID 只能由字母与数字组成' }
      ]
    },
    {
      label: 'Token',
      name: 'token',
      node: Input,
      value: appdata.token,
      rules: [
        { pattern: /^[a-zA-Z0-9]+$/, message: 'token 只能由字母与数字组成' }
      ]
    },
    {
      label: 'AES_KEY',
      name: 'aesKey',
      node: Input,
      value: appdata.aesKey,
      rules: [
        { pattern: /^[a-zA-Z0-9]+$/, message: 'AES_KEY 只能由字母与数字组成' }
      ]
    },
    ...tplFields,
    {
      label: '小程序码',
      name: 'qrCode',
      render: () => <img src={qrCode} style={{ width: '240px' }} alt=""/>,
      value: qrCode,
    },
    {
      action: true,
      render: () => {
        return (
          <div className={Style['flex-box']}>
            <div className={Style['flex-item']}>
              <img src="" alt="" style={{ width: '128px' }}/>
            </div>
            <div className={Style['flex-auto']}>
              <Button type="primary" ghost onClick={showModal}>验证</Button>
            </div>
            <Modal
              title="填写首页地址"
              visible={visible}
              onOk={handleModalOk}
              onCancel={() => changeVisible(false)}
            >
              <Input value={path} onChange={e => changePath(e.target.value)}></Input>
            </Modal>
          </div>
        )
      }
    },
  ]

  const checkTPLData = (submitData) => {
    let errors = []

    const tplData = Object.keys(submitData).map((key) => {
      const { tplId, fieldNum, tplFields, isSubscribe, ...left } = submitData[key]
      const tplType = (props.tplTyps || []).filter(x => x.code === key)[0] || {}

      if (isSubscribe) {
        if (tplId && !tplFields) {
          errors.push(`请填写${tplType.name}模板字段内容`)
          return
        }
      } else if (tplId && !fieldNum) {
        errors.push(`请填写${tplType.name}模板字段数`)
        return
      }

      return {
        ...submitData[key],
        tplType: tplType.code,
      }
    })

    return [tplData, errors]
  }

  const handleSubmit = (val, setSubmitting) => {
    // 校验字段
    const { tpl, ...otherData} = val

    const [tplData, errors] = checkTPLData(tpl)

    if (errors.length > 0) {
      notification.error({ message: errors[0] })
      return
    }

    const data = {
      ...appdata,
      ...otherData,
      qrCode: qrCode || appdata.appdata,
      orgId: user.orgId,
      tpls: tplData,
    }

    setSubmitting(true)

    saveMiniapp({ data }).then((miniapp) => {
      
      if (typeof props.onChange === 'function') {
        props.onChange({ ...user, miniapp })
      }

      setSubmitting(false)

      notification.success({ message: '保存小程序信息成功' })
    }).catch(x => setSubmitting(false))
  }

  const handleCancel = () => {
    if (typeof props.onCancel === 'function') {
      props.onCancel()
    }
  }

  return (<XForm wrappedComponentRef={handleForm} onSubmit={handleSubmit} onCancel={handleCancel} fields={fields}></XForm>)
}

export default Miniapp;
