import React, { useEffect, useState, useCallback, useRef } from 'react'
import { useModel } from 'umi'
import { Form, Input, Button,message } from 'antd';
import ProCard from '@ant-design/pro-card';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import QRCode from 'qrcodejs2'
import { getDetail, saveOrg, updateOrg,saveOrgUser,getOrgAdminDetail } from '@/services/org';
import md5 from 'md5';

export default (props) => {
  const { history } = props;
  const { id } = history.location.query;
  const { initialState } = useModel('@@initialState');

  const [form] = Form.useForm();
  const [formData, setFormData] = useState()
  const [loading, setLoading] = useState(false)
  const qrcodeRef = useRef()
  const linkRef = useRef()

  const [adminForm] = Form.useForm();
  const [adminFormData, setAdminFormData] = useState()
  const [adminLoading, setAdminLoading] = useState(false)

  const downloadQrcode = useCallback(() => {
    if (linkRef.current) {
      linkRef.current.click();
    }
  }, [])
  const onFinish = (values) => {
    setLoading(true)
    if (id) {
      updateOrg(id, values).then(() => {
        setLoading(false);
        history.go(-1);
      }).catch(() => {
        setLoading(false);
      })
    } else {
      saveOrg(values).then(() => {
        setLoading(false);
        history.go(-1);
      }).catch(() => {
        setLoading(false);
      })
    }
  };
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  const onAdminFinish=(values)=>{
    if (!/^1[0-9]{10}$/.test(values.phone)) {
      message.warning('请输入正确的十一位手机号');
      setLoading(false);
      return false;
    }
    var data={...adminFormData,...values,password:md5(values.password),isAdmin:true};
    setAdminLoading(true)
    saveOrgUser(id,data).then(res=>{
      message.success('保存成功');
      history.go(-1);
      setAdminLoading(false)
    }).catch(err=>{
      console.log(err);
      setAdminLoading(false)
    })
  }

  useEffect(() => {
    if (id) {
      getDetail(id).then(res => {
        setFormData(res);
        form.setFieldsValue(res);

        // 初始化二维码
        const qrcode = new QRCode(qrcodeRef.current, {
          width: 160,
          height: 160, // 高度
          text: initialState.report_url + '?org=' + id
        })
        const canvas = qrcodeRef.current.querySelector('canvas')
        // 创建下载链接
        const aElement = document.createElement('a');
        linkRef.current = aElement;
        linkRef.current.download = res.orgName + '.png'
        linkRef.current.href = canvas.toDataURL('image/jpg')
      })
      getOrgAdminDetail(id).then((res)=>{
        setAdminFormData(res);
        adminForm.setFieldsValue(res);
      })
    }
  }, [id, form])

  return (
    <PageHeaderWrapper>
      <ProCard tabs={{ type: 'card' }} style={{ minHeight: '700px' }}>
        <ProCard.TabPane key={1} tab="基本信息">
          <div style={{ maxWidth: '600px' }}>
            <Form
              name="basic"
              form={form}
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 16 }}
              initialValues={formData}
              onFinish={onFinish}
              onFinishFailed={onFinishFailed}
              autoComplete="off"
            >
              <Form.Item
                label="企业名称"
                name="orgName"
                rules={[{ required: true, message: '请填写企业名称!' }]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                label="权重"
                name="weight"
                rules={[{ required: true, message: '请填写企业名称!' }]}
              >
                <Input type='number' min='0' />
              </Form.Item>
              <Form.Item label=' ' colon={false} wrapperCol={{ offset: 3 }}>
                <div ref={qrcodeRef} />
              </Form.Item>
              <Form.Item label=' ' colon={false} >
                <Button type="primary" htmlType="submit" loading={loading}>
                  保存
                </Button>
                <Button style={{ margin: '0 32px' }} onClick={downloadQrcode} >
                  下载二维码
                </Button>
                <Button onClick={()=>{history.go(-1);}} >返回</Button>
              </Form.Item>
            </Form>
          </div>
        </ProCard.TabPane>
        <ProCard.TabPane disabled={!id} key={2} tab='管理员'>
          <div style={{ maxWidth: '600px' }}>
            <Form
              form={adminForm}
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 16 }}
              initialValues={adminFormData}
              onFinish={onAdminFinish}
            >
              <Form.Item
                label="姓名"
                name="userName"
                rules={[{ required: true, message: '请填写管理员姓名!' }]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                label="手机号"
                name="phone"
                rules={[{ required: true, message: '请填写手机号!' }]}
              >
                <Input maxLength={11}/>
              </Form.Item>
              <Form.Item
                label="登录账号"
                name="loginName"
                rules={[{ required: true, message: '请填写登录账号!' }]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                label="密码"
                name="password"
                rules={[{ required: true, message: '请填写密码!' }]}
              >
                <Input />
              </Form.Item>
              <Form.Item label=' ' colon={false} >
                <Button type="primary" htmlType="submit" loading={adminLoading}>
                  保存
                </Button>
                <Button style={{marginLeft:'32px'}} onClick={()=>{history.go(-1);}}>返回</Button>
              </Form.Item>
            </Form>
          </div>

        </ProCard.TabPane>
      </ProCard>
    </PageHeaderWrapper>
  )
}
