import React, { useState, useImperativeHandle, forwardRef, useMemo, useEffect } from 'react'
import { Modal, Form, Input, Table, Button, Switch, Upload, Radio, Checkbox, message, Tag, Spin } from 'antd'
import { UploadOutlined, FileOutline, ArrowDownOutlined } from '@ant-design/icons'
import styles from './index.less'
import QRCode from 'qrcode.react'
import { GetDeviceQRCodeConfig, EditOrAddDeviceQRCodeConfig } from '@/services/flow/flow'
import html2canvas from 'html2canvas'
import JSZip from 'jszip'
import { saveAs } from 'file-saver'

const downloadFileUrl = '/PandaWorkFlow/WorkFlow/AccountManage/DownloadFiles'

const QRCodeView = (props) => {

  const { style, values, active, isBatch, id } = props

  const QRCodeValue = useMemo(() => {
    return `${window.location.origin}/civ_mobile/product/workflow/equipment/devicePatrol?DeviceCode=${values.DeviceCode}&AccountName=${values.AccountName}`
  }, [values.DeviceCode, values.AccountName])

  return (
    <div className={styles.QRCode} style={style || {}} id={id}>
      <div className={styles.company} active={`${active === 'CorporateName'}`}>{values.CorporateName}</div>
      <div className={styles.title} active={`${active === 'Title'}`}>{values.Title}</div>
      <div className={styles.QR}>
        <QRCode
          value={QRCodeValue}
          size={158} // 二维码的大小
          level="H" // 设置容错等级为最高
          fgColor="#000000" // 二维码的颜色
          style={{
            margin: 'auto',
          }}
        />
        <div className={styles.QRLogo} active={`${active === 'IsSystemLogo'}`}>
          {
            values.IsSystemLogo === '系统LOGO' ? (
              <img style={{ width: '100%', height: '100%' }} src={`${window.origin}/civweb4/assets/images/icon/%E7%86%8A%E7%8C%AB-%E8%93%9D%E8%89%B2.png`} />
            ) : (
              <img
                style={{ width: '100%', height: '100%', display: values.LabelLogoUrl ? 'block' : 'none' }}
                src={`${window.origin}${downloadFileUrl}?filePath=${values.LabelLogoUrl}`}
              />
            )
          }
        </div>
      </div>
      <div className={styles.pandaLogo} active={`${active === 'IsPandaLogo'}`}>
        <div className={styles.pandaLogoC} style={{ display: values.IsPandaLogo ? 'block' : 'none' }}></div>
      </div>
      <div className={styles.info}>
        {isBatch ? <span className={styles.tag} type={'设备名称'}>【设备名称】</span> : <div className={styles.DeviceName}>{values.DeviceName}</div>}
        <div style={{ margin: '2%' }}></div>
        {isBatch ? <span className={styles.tag} type={'设备编号'}>【设备编号】</span> : <div className={styles.DeviceCode}>{values.DeviceCode}</div>}
      </div>
    </div>
  )
}

const QRCodeDesign = (props, ref) => {

  useImperativeHandle(ref, () => ({
    open
  }))

  const [record, setRecord] = useState({})
  const [visible, setVisible] = useState(false)
  const [show, setShow] = useState(false)
  const [loading, setLoading] = useState(false)
  const [dataSource, setDataSource] = useState([])
  const [parentQRCode, setParentQRCode] = useState({})
  const [isBatch, setIsBatch] = useState(true)
  const [showList, setShowList] = useState([])
  const [values, setValues] = useState({})
  const [currentRow, setCurrentRow] = useState({})
  const [minVisible, setMinVisible] = useState(false)
  const [active, setActive] = useState('')
  const [form] = Form.useForm()

  const columns = useMemo(() => {
    return [
      {
        title: '序号',
        dataIndex: 'name',
        key: 'name',
        width: 80,
        align: 'center',
        render: (r, t, i) => i + 1
      },
      {
        title: '设备名称',
        dataIndex: 'DeviceName',
        key: 'DeviceName',
        align: 'center',
      },
      {
        title: '设备编号',
        dataIndex: 'DeviceCodeAlias',
        key: 'DeviceCodeAlias',
        align: 'center',
        render: (value) => <Tag color="processing">{value}</Tag>
      },
      {
        title: '设备类型',
        dataIndex: 'AccountName',
        key: 'AccountName',
        align: 'center',
      },
      {
        title: '设备二维码',
        dataIndex: 'Title',
        key: 'Title',
        align: 'center',
        render: (_, row) => {
          return (
            <div
              className={styles.qrCodeCell}
              onClick={() => {
                setMinVisible(true)
                setCurrentRow(row)
              }}
            >
              <QRCodeView
                id={row.DeviceCode}
                values={{
                  CorporateName: row.CorporateName || '熊猫水务',
                  Title: row.Title || '设备二维码',
                  IsSystemLogo: Boolean(row.IsSystemLogo) ? '系统LOGO' : '自定义LOGO',
                  IsPandaLogo: Boolean(row.IsPandaLogo),
                  LabelLogoUrl: row.LabelLogoUrl,
                  DeviceName: row.DeviceName,
                  DeviceCode: row.DeviceCode,
                  AccountName: row.AccountName,
                }}
                isBatch={false}
                style={{ width: '310px', height: '490px', zoom: 0.15, margin: '0 auto' }}
              />
            </div>
          )
        }
      },
      {
        title: '操作',
        dataIndex: 'name',
        key: 'name',
        width: 200,
        align: 'center',
        render: (_, row) => {
          return (
            <div>
              <Button type='link' icon={<span className={styles.downIcon}></span>} onClick={() => downFile(row)}>下载</Button>
              {/* <Button type='link' onClick={() => editStyle(row)}>样式编辑</Button> */}
            </div>
          )
        }
      },
    ]
  }, [dataSource])

  const option = {
    name: 'file',
    action: `${window.location.origin} /PandaWorkFlow/WorkFlow/AccountManage/UploaderFiles`,
    listType: 'picture',
    withCredentials: true,
    maxCount: 1,
    showUploadList: {
      showRemoveIcon: true,
      showDownloadIcon: true,
    },
    beforeUpload(file, fileList) {
      /** @Tips: 解决提交文件中存在特殊字符的问题 */
      let _continueUpload = true;
      let _msg = {
        type: 'success',
        content: '上传成功！',
      };
      // fileList.forEach(item => {
      //   let _msgObject = filenameVerification(item);
      //   if (_msgObject.type === 'error') {
      //     _continueUpload = false;
      //     _msg = {
      //       type: 'error',
      //       content: '上传失败！文件名不符合规则！',
      //     };
      //   }
      // });
      _msg.type === 'error' ? message[_msg.type](_msg.content) : ''
      return _continueUpload;
    },
    onChange: ({ file, fileList, event }) => {
      if (!file.size) {
        return
      }
      // 检验名字，名字不通过不允许显示
      // if (filenameVerification(file).type === 'error') return false;
      // 返回的链接在file.response内；不设置url，预览图表不可点击
      if (file.status === 'done' && file.response.code === 0) {
        file.url = `${window.origin}${downloadFileUrl}?filePath=${file.response.data}`
        file.sourcePath = file.response.data;
        message.success('上传成功！')
      } else if (file.status === 'done' && file.response.code !== 0) {
        file.status = 'error';
        message.error('上传失败！')
      }
      if (Array.isArray(fileList)) {
        setShowList(fileList)
      } else {
        setShowList([])
      }
      if (file.status === 'done') {
        setValues({ ...values, LabelLogoUrl: fileList.map(v => v.sourcePath).join(',') })
        form.setFieldsValue({ LabelLogoUrl: fileList.map(v => v.sourcePath).join(',') })
      }
    },
    // onPreview: async (file) => {

    // },
    onRemove: (file) => {
      setShowList([])
      form.setFieldsValue({ LabelLogoUrl: '' })
      setValues({ ...values, LabelLogoUrl: '' })
    },
  }

  const downFile = async (row) => {
    setLoading(true)
    const canvas = document.getElementById(row.DeviceCode);
    const can = await html2canvas(canvas, { allowTaint: false, useCORS: true, width: 310, scale: 2 })
    console.log('can', can.toDataURL())
    let a = document.createElement('a');
    a.setAttribute('href', can.toDataURL()); //toDataUrl：将canvas画布信息转化为base64格式图片
    a.setAttribute('download', `${row.DeviceName}_${row.DeviceCode}`); //这个是必须的，否则会报错
    a.setAttribute('target', '_self');
    a.click();
    setLoading(false)
  }

  const editStyle = (row) => {
    setCurrentRow(row)
    let values = {
      CorporateName: row.CorporateName || '熊猫水务',
      Title: row.Title || '设备二维码',
      IsSystemLogo: Boolean(row.IsSystemLogo) ? '系统LOGO' : '自定义LOGO',
      IsPandaLogo: Boolean(row.IsPandaLogo),
      LabelLogoUrl: row.LabelLogoUrl,
      DeviceName: row.DeviceName,
      DeviceCode: row.DeviceCode,
      AccountName: row.AccountName,
    }
    setValues(values)
    form.setFieldsValue(values)
    setIsBatch(false)
    setShow(true)
  }

  const valueToList = (presetValue) => {
    let fileList = []
    if (presetValue) {
      let list = presetValue ? presetValue.split(',') : []
      for (let i = 0; i < list.length; i++) {
        if (list[i]) { // @Tips: 直接过滤掉名字中有异常字符的文件
          let uid = i + '_' + Math.random()
          let _obj = {
            uid: uid,
            name: list[i].split('\\').reverse()[0],
            type: 'image/jpeg',
            status: 'done',
            url: `${window.origin}${downloadFileUrl}?filePath=${list[i]}`,
            sourcePath: list[i],
            originFileObj: { "uid": uid },
            "response": { "code": 0, "msg": "Ok", "data": list[i], "stackTrace": null },
            "xhr": {},
          };
          _obj.thumbUrl = `${window.origin}${downloadFileUrl}?filePath=${list[i]}`
          fileList.push(_obj);
        }
      }
    }
    return fileList
  }

  const getDataSource = async (record) => {
    setLoading(true)
    const { code, data } = await GetDeviceQRCodeConfig({ accountName: record.AccountName, accountTableName: record.AccountTableName })
    if (code === 0) {
      setDataSource(data?.DeviceQRCodeConfigList || [])
      setParentQRCode(data?.AccountQRCodeConfig || {})
      const { CorporateName, Title, IsPandaLogo, IsSystemLogo, LabelLogoUrl } = data?.AccountQRCodeConfig || {}
      let values = {
        CorporateName: CorporateName || '熊猫水务',
        Title: Title || '设备二维码',
        IsSystemLogo: Boolean(IsSystemLogo) ? '系统LOGO' : '自定义LOGO',
        IsPandaLogo: Boolean(IsPandaLogo),
        LabelLogoUrl: LabelLogoUrl
      }
      setShowList(valueToList(LabelLogoUrl))
      form?.setFieldsValue(values)
      setValues(values)
    }
    setLoading(false)
  }

  const open = (record) => {
    setActive('')
    setRecord(record)
    setShow(false)
    setVisible(true)
    getDataSource(record)
  }

  const onValuesChange = (values) => {
    form.setFieldsValue(values)
    setValues(form.getFieldsValue(true))
  }

  const bathEdit = () => {
    setIsBatch(true)
    setShow(true)
  }

  const dataURLtoBlob = (dataurl) => {
    var arr = dataurl.split(',');
    var mime = arr[0].match(/:(.*?);/)[1];
    var bstr = atob(arr[1]);
    var n = bstr.length;
    var u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
  }

  const Allexport = async () => {
    setLoading(true)
    let zip = new JSZip()
    if (dataSource.length) {
      for (let i = 0; i < dataSource.length; i++) {
        let row = dataSource[i]
        const canvas = document.getElementById(row.DeviceCode);
        const can = await html2canvas(canvas, { allowTaint: false, useCORS: true, width: 310, scale: 2 })
        let img = new Image()
        img.src = can.toDataURL('image/png')
        zip.file(`${row.DeviceName}_${row.DeviceCode}.png`, dataURLtoBlob(img.src))
      }
    }
    zip.generateAsync({ type: 'blob' }).then((res) => {
      saveAs(res)
      setLoading(false)
    })
  }

  const save = async () => {
    let params = {
      ID: parentQRCode.ID,
      accountName: parentQRCode.AccountName,
      deviceCode: null,
      deviceCodeAlias: null,
      deviceName: null,
      corporateName: values.CorporateName,
      title: values.Title,
      labelLogoUrl: values.LabelLogoUrl,
      isSystemLogo: values.IsSystemLogo === '系统LOGO' ? 1 : 0,
      isPandaLogo: values.IsPandaLogo ? 1 : 0,
    }
    const { code, data } = await EditOrAddDeviceQRCodeConfig(params)
    if (code === 0) {
      message.success('保存成功!')
      setShow(false)
      getDataSource(record)
    } else {
      message.error('保存失败!')
    }
  }

  const footer = (
    <div>
      {
        !show ? (
          <>
            <Button type='primary' onClick={() => bathEdit()}>样式编辑</Button>
            <Button onClick={() => Allexport()}>全部导出</Button>
          </>
        ) : (
          <>
            <Button onClick={() => setShow(false)}>返回</Button>
            <Button type='primary' onClick={() => save()}>保存</Button>
          </>
        )
      }
    </div>
  )

  return (
    <Modal
      wrapClassName={styles.QRCodeModal}
      visible={visible}
      onCancel={() => setVisible(false)}
      title={<div className={styles.QRCodeTitle}>{!show ? '设备列表' : '样式编辑器'}</div>}
      width={'65%'}
      bodyStyle={{ width: '100%', height: '650px', padding: '10px', background: show ? '#F6F9FC' : 'white' }}
      footer={footer}
    >
      <div className={styles.QRCodeList} style={{ display: show ? 'none' : 'block' }}>
        <Spin spinning={loading} tip="下载中...">
          <div className={styles.table}>
            <Table
              size='small'
              columns={columns}
              dataSource={dataSource}
              pagination={false}
              scroll={{ y: 570 }}
            />
          </div>
        </Spin>
      </div>
      <div className={styles.QRCodeDesign} style={{ display: show ? 'flex' : 'none' }}>
        <div className={styles.left}>
          <div className={styles.header}>
            <div className={styles['h-icon']}></div>
            <div className={styles['h-text']}>编辑字段</div>
            <div className={styles['h-background']}></div>
            <div className={styles['h-bgArrow']}></div>
          </div>
          <div className={styles.content}>
            <Form
              labelCol={{ flex: '88px' }}
              form={form}
              initialValues={values}
              onValuesChange={onValuesChange}
            >
              <div className={styles.gName}>基础信息</div>
              <div style={{ padding: '10px 10px 0 10px' }}>
                <Form.Item label="公司名称" name="CorporateName">
                  <Input onFocus={() => setActive('CorporateName')} placeholder="请选择公司名称" allowClear />
                </Form.Item>
                <Form.Item label="标题" name="Title">
                  <Input onFocus={() => setActive('Title')} placeholder="请选择标题" allowClear />
                </Form.Item>
                <Form.Item label="设备名称" name="DeviceName">
                  {isBatch ? <span className={styles.tag} type={'设备名称'}>【设备名称】</span> : <Input placeholder="" allowClear />}
                </Form.Item>
                <Form.Item label="设备编号" name="DeviceCode">
                  {isBatch ? <span className={styles.tag} type={'设备编号'}>【设备编号】</span> : <Input placeholder="" allowClear />}
                </Form.Item>
              </div>
              <div className={styles.gName}>标签LOGO</div>
              <div style={{ padding: '10px 10px 0 10px' }}>
                <Form.Item label="LOGO" name="IsSystemLogo">
                  <Radio.Group onChange={() => setActive('IsSystemLogo')}>
                    <Radio value="自定义LOGO">自定义LOGO</Radio>
                    <Radio value="系统LOGO">系统LOGO</Radio>
                  </Radio.Group>
                </Form.Item>
                <Upload.Dragger
                  {...option}
                  className="upload-list-inline"
                  fileList={showList}
                  accept={['.bmp', '.gif', '.jpeg', '.tiff', '.png', '.svg', '.jpg', '.webp']}
                  disabled={values.IsSystemLogo === '系统LOGO'}
                >
                  <div>
                    <div className={styles.uploadIcon}></div>
                    {
                      !showList.length ? (
                        <div>
                          <div className={styles.uploadBtn}>选择文件</div>
                          <div className="ant-upload-hint">支持上传文件为:jpg、png、svg</div>
                        </div>
                      ) : null
                    }
                  </div>
                </Upload.Dragger>
                <Form.Item label="熊猫LOGO" name="IsPandaLogo" valuePropName="checked" style={{ marginTop: '10px' }}>
                  <Switch onChange={() => setActive('IsPandaLogo')} checkedChildren="启用" unCheckedChildren="禁用" />
                </Form.Item>
              </div>
            </Form>
          </div>
        </div>
        <div className={styles.right}>
          <div className={styles.box}>
            <QRCodeView values={values} active={active} isBatch={isBatch} />
          </div>
        </div>
      </div>
      <Modal
        wrapClassName={styles.QRCodeMinModal}
        onCancel={() => setMinVisible(false)}
        visible={minVisible}
        footer={null}
        width={310}
        bodyStyle={{ width: '100%', height: '491px', padding: '0' }}
      >
        <QRCodeView
          id={currentRow.DeviceCode}
          values={{
            CorporateName: currentRow.CorporateName || '熊猫水务',
            Title: currentRow.Title || '设备二维码',
            IsSystemLogo: Boolean(currentRow.IsSystemLogo) ? '系统LOGO' : '自定义LOGO',
            IsPandaLogo: Boolean(currentRow.IsPandaLogo),
            LabelLogoUrl: currentRow.LabelLogoUrl,
            DeviceName: currentRow.DeviceName,
            DeviceCode: currentRow.DeviceCode,
            AccountName: currentRow.AccountName,
          }}
          isBatch={false}
        />
      </Modal>
    </Modal>
  )
}

export default forwardRef(QRCodeDesign)