import React from 'react'
import { Form, InputNumber, Select, Tabs, Radio, Row, Col, Empty, Checkbox, Input, message, Divider, Popover } from 'antd';
import { FontColorsOutlined } from '@ant-design/icons';
import { Spinner } from "../../../../../components";
import Button from '../../../../../components/Button'
import { CloseIcon } from "../../../../../components/icons";
import { pageOptions, sizeOptions, fontSizeOptions, fontFamilyOptions, IDPTableValue, duplexPrintOptions } from '../../types';
import { detailPrint } from '../../../../../utils/print';
import { RendererEnv } from '../../../../../env';
import { Api } from '../../../../../types';
import moment from 'moment';
import { PrintSchemaUI, DetailOptionValues, DetailSettingValues, DetailTableValues, PrintContent } from './types';
import { buildPrintFlowSchema, buildPrintFormSchema, buildPropertyUI, chunkArray, createHtml, findLabel, getDetailTableValues } from './utils';
import { buildDetailTemplate } from '../../../../../utils/print/util';
import { tokenize } from 'amis-formula';
import TableSetting from './TableSetting';

const { Option } = Select;

interface IProps {
  superRole: boolean
  env: RendererEnv
  printers: string[]
  printInfo?: { title: string, subTitle: string, extraTitle: string, printFlow?: boolean, processNodeList: any[] }
  callbackApi?: any
  actionType?: 'flow-print' | 'form-print' | 'batch-print'
  [key: string]: any;
}

interface IState extends DetailSettingValues, DetailOptionValues, DetailTableValues {
  previewLoading: boolean
  saveLoading: boolean
  showEmpty: boolean
  isDynamicTitle: boolean
  isDynamicSubTitle: boolean
  dynamicTitle: string
  dynamicSubTilteList: string[]
  subTitle?: string
}

export default class DetailPrint extends React.Component<IProps, IState> {

  formName: string
  reportTitleSql?: string
  reportSubTitleSql?: string
  flowPrint: boolean
  batchPrint: boolean
  cacheFormSchema?: any[]
  cacheSchema?: any
  cacheData?: any[]

  constructor(props: IProps) {
    super(props)
    this.formName = props.name
    const setting = localStorage.getItem('SF_PrintSetting') ?? '{}'
    const settingObj = JSON.parse(setting)
    this.flowPrint = props.actionType === 'flow-print' || props.printInfo?.printFlow === true
    this.batchPrint = props.actionType === 'batch-print'

    this.state = {
      previewLoading: false,
      saveLoading: false,
      showEmpty: true,
      isDynamicTitle: false,
      isDynamicSubTitle: false,
      dynamicTitle: '',
      dynamicSubTilteList: [],
      //
      printer: settingObj.printer ?? props.printers[0],
      page: settingObj.page ?? 'A4',
      width: settingObj.width ?? 210,
      height: settingObj.height ?? 297,
      top: settingObj.top ?? 10,
      bottom: settingObj.bottom ?? 10,
      left: settingObj.left ?? 10,
      right: settingObj.right ?? 10,
      duplex: 0,
      direction: settingObj.direction ?? 'vertical',
      numberOfPage: 1,
      copies: settingObj.copies ?? 1,
      //
      showTitle: true,
      title: props.printInfo?.title ?? (props.dialogTitle ?? ''),
      titleFontSize: 16,
      titleFontFamily: '宋体',
      showDynamicSubTitles: false,
      dynamicSubTiltes: [],
      subTitleFontSize: 12,
      subTitleFontFamily: '宋体',
      headerTitle: '',
      headerFontSize: 12,
      headerFontFontFamily: '宋体',
      titleAllPrint: true,
      subTitleAllPrint: true,
      showHeader: true,
      showFooter: true,
      footerFontSize: 13,
      footerFontFamily: '宋体',
      showHeaderLine: true,
      showFooterLine: true,
      showDate: true,
      showPageNum: true,
      showPrinter: true,
      showLogo: true,
      showBarCode: false,
      showQRCode: false,
      numberBreak: true,
      rowPadding: 0,
      colPadding: 0,
      borderWidth: 2,
      lineWidth: 1,
      contentFontSize: 12,
      contentFontFamily: '宋体',
      labelWidthPercent: 30,
      //
      detailTableValues: []
    }
  }

  componentDidMount() {
    this.handleGetSetting()
  }

  componentWillUnmount() {
    const settingValues: DetailSettingValues = {
      printer: this.state.printer,
      page: this.state.page,
      width: this.state.width,
      height: this.state.height,
      top: this.state.top,
      bottom: this.state.bottom,
      left: this.state.left,
      right: this.state.right,
      duplex: this.state.duplex,
      direction: this.state.direction,
      numberOfPage: this.state.numberOfPage,
      copies: this.state.copies,
    }
    localStorage.setItem('SF_PrintSetting', JSON.stringify(settingValues))
  }

  async handleGetSetting() {
    let schema, formData
    if (this.batchPrint) {
      const [printSchema, printData] = await Promise.all([this.getBatchPrintSchema(), this.getBatchPrintData()])
      schema = printSchema
      formData = printData[0]
    } else {
      schema = this.props.$schema
      formData = this.props.data
      if (schema.initApi) {
        delete schema.initApi
      }
    }
    const tableValues = await getDetailTableValues(schema, formData, this.props.env.fetcher)

    const payload = await this.props.env.fetcher(`/api/v1/${this.flowPrint ? 'flow' : 'form'}/print/${this.formName}/select`)
    const data = payload.data
    if (payload.ok && data != null) {
      this.reportTitleSql = data.reportTitleSql
      this.reportSubTitleSql = data.reportSubTitleSql
      const isDynamicTitle = data.isDynamicTitle ?? false
      const isDynamicSubTitle = data.isDynamicSubTitle ?? false

      this.setState(pre => {
        const defaultValues: IDPTableValue[] = data.detailTableValues
        let detailTableValue = tableValues
        if (data.isGlobalSetting) {
          detailTableValue = tableValues.map(values => ({ ...values, fontSize: data.fieldTableFontSize ?? values.fontSize, fontFamily: data.fieldTableFamily ?? values.fontFamily }))
        } else if (Array.isArray(defaultValues)) {
          detailTableValue = tableValues.map(values => {
            const target = defaultValues.find(item => item.name == values.name)
            if (target) {
              return {
                ...target,
                columns: values.columns.map(column => {
                  const temp = target.columns.find(item => item.name == column.name)
                  return temp ? { ...column, printType: temp.printType } : column
                })
              }
            }
            return values
          })
        }
        return ({
          ...pre,
          ...data,
          title: isDynamicTitle ? data.reportTitle ?? pre.title : data.title ?? pre.title,
          dynamicTitle: isDynamicTitle ? data.reportTitle : data.title,
          dynamicSubTilteList: isDynamicSubTitle ? data.reportSubTitle ?? [] : [],
          showDynamicSubTitles: data.showDynamicSubTitles ?? pre.showDynamicSubTitles,
          dynamicSubTiltes: data.reportSubTitle?.filter((val: string, index: number) => data.dynamicSubTiltes?.includes(index)) ?? pre.dynamicSubTiltes,
          detailTableValues: detailTableValue
        })
      }, () => { this.handleDetailPrint(true) })
    } else {
      this.setState({ detailTableValues: tableValues }, () => { this.handleDetailPrint(true) })
    }
  }

  async handleSaveSetting() {
    const api: Api = { method: 'post', url: `/api/v1/${this.flowPrint ? 'flow' : 'form'}/print/${this.formName}/modify` }
    const {
      showHeader, showHeaderLine, showFooter, showFooterLine, headerTitle, titleAllPrint, subTitleAllPrint,
      lineWidth, borderWidth, rowPadding, colPadding, dynamicSubTilteList, showTitle, title, showDynamicSubTitles, dynamicSubTiltes, subTitle,
      showDate, showPageNum, showPrinter, showLogo, detailTableValues, showBarCode, showQRCode, numberBreak, labelWidthPercent,
      contentFontSize, contentFontFamily, titleFontSize, titleFontFamily, subTitleFontSize, subTitleFontFamily,
      headerFontSize, headerFontFontFamily, footerFontSize, footerFontFamily
    } = this.state
    const titleIndex = dynamicSubTiltes.map(val => dynamicSubTilteList.findIndex(title => val == title))
    const settingValues = {
      showHeader, showHeaderLine, showFooter, showFooterLine, headerTitle, titleAllPrint, subTitleAllPrint,
      lineWidth, borderWidth, rowPadding, colPadding, contentFontSize, contentFontFamily, labelWidthPercent,
      titleFontSize, titleFontFamily, subTitleFontSize, subTitleFontFamily, headerFontSize, headerFontFontFamily, footerFontSize, footerFontFamily,
      showTitle, title, showDynamicSubTitles, dynamicSubTiltes: titleIndex, subTitle, showDate, showPageNum, showPrinter, showLogo, showQRCode, showBarCode, numberBreak,
      detailTableValues, reportTitleSql: this.reportTitleSql, reportSubTitleSql: this.reportSubTitleSql
    }
    this.setState({ saveLoading: true })
    const payload = await this.props.env.fetcher(api, settingValues).finally(() => { this.setState({ saveLoading: false }) })
    if (payload.ok) {
      message.success(payload.msg)
    }
  }

  async handleDeleteSetting() {
    const api: Api = { method: 'delete', url: `/api/v1/${this.flowPrint ? 'flow' : 'form'}/print/${this.formName}/delete` }
    const payload = await this.props.env.fetcher(api)
    if (payload.ok) {
      message.success(payload.msg)
    }
  }

  savePrintInfo() {
    const { env: { fetcher }, data, ctx, callbackApi } = this.props
    if (!callbackApi) return
    const PRINT_TIME = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
    const postData = this.batchPrint ? { ids: ctx.ids, PRINT_TIME } : { ...data, PRINT_TIME }
    fetcher(callbackApi, postData)
  }

  async getBatchPrintSchema() {
    const { env, schemaApi, ctx } = this.props
    if (this.cacheSchema) return this.cacheSchema
    const payload = await env.fetcher(schemaApi, ctx)
    if (payload.ok && payload.data) {
      const data = payload.data
      if (data.name) {
        this.formName = data.name
      }
      if (data.initApi) {
        delete data.initApi
      }
      this.cacheSchema = data
      return data
    } else {
      message.error(payload.msg)
    }
    return null
  }

  async getBatchPrintData() {
    const { env, dataApi, ctx } = this.props
    if (this.cacheData) return this.cacheData
    const payload = await env.fetcher(dataApi, ctx)
    if (payload.ok && Array.isArray(payload.data)) {
      this.cacheData = payload.data
      return payload.data as any[]
    }
    return []
  }

  async getPrintFormSchema(schema: any, data: object, fetcher: RendererEnv['fetcher']) {
    const result = this.cacheFormSchema ?? await buildPrintFormSchema(schema, data, fetcher)
    this.cacheFormSchema = result
    return result
  }

  setPrintFormSchemaData(schemas: any[], data: object) {
    return schemas.map<PrintSchemaUI>(schema => {
      if (schema.type === 'property') {
        const items = buildPropertyUI(schema, data)
        return { type: 'property', body: items, column: schema.column, data: data, label: schema.title }
      } else {
        return {
          type: 'table',
          name: schema.name,
          label: schema.aliasTitle,
          body: { columns: schema.columns.filter((column: any) => column.name !== 'operation'), data: schema.data }
        }
      }
    })
  }

  async handleDetailPrint(preview: boolean) {
    const { codeField, env, $schema, data: formData, printInfo } = this.props
    const codeLabel = findLabel(codeField, this.props.body)?.label ?? ''
    const userName = JSON.parse(sessionStorage.getItem('userInfo') ?? '{}').user_name ?? ''

    this.setState({ previewLoading: true, showEmpty: false })

    if (this.batchPrint) {
      const [schema, datas] = await Promise.all([this.getBatchPrintSchema(), this.getBatchPrintData()])
      const formSchema = await this.getPrintFormSchema(schema, datas[0], env.fetcher)
      const chunkData = chunkArray(datas.slice(0, preview ? 10 : undefined), this.state.numberOfPage)
      const template = chunkData.map(datas => {
        return datas.map((data, index) => {
          const options: DetailSettingValues & DetailOptionValues = {
            ...this.state,
            title: tokenize(this.state.title, data),
            dynamicSubTiltes: (this.state.isDynamicSubTitle ? this.state.dynamicSubTiltes : [this.state.subTitle ?? '']).map(item => tokenize(item, data))
          }
          const formSchemaWithData = this.setPrintFormSchemaData(formSchema, data)
          const printContent: PrintContent = {
            userName,
            codeLabel,
            codeValue: data[codeField],
            htmlContent: createHtml({ form: formSchemaWithData }, this.state),
          }
          return buildDetailTemplate(this.state, options, printContent, index, this.state.numberOfPage, true)
        })
      })
      detailPrint(preview, this.state, template, () => {
        if (!preview) {
          message.success('打印任务发送成功')
          this.savePrintInfo()
        }
        this.setState({ previewLoading: false })
      })
    } else {
      const options: DetailSettingValues & DetailOptionValues = {
        ...this.state,
        title: tokenize(this.state.title, formData),
        dynamicSubTiltes: (this.state.isDynamicSubTitle ? this.state.dynamicSubTiltes : [this.state.subTitle ?? '']).map(item => tokenize(item, formData))
      }
      const formSchema = await this.getPrintFormSchema($schema, formData, env.fetcher)
      const formSchemaWithData = this.setPrintFormSchemaData(formSchema, formData)
      const flowSchema = buildPrintFlowSchema(printInfo)
      const printContent: PrintContent = {
        userName,
        codeLabel,
        codeValue: formData?.[codeField],
        subTitle: printInfo?.subTitle,
        extraTitle: printInfo?.extraTitle ?? '',
        htmlContent: createHtml({ form: formSchemaWithData, flow: flowSchema }, this.state),
      }
      const template = buildDetailTemplate(this.state, options, printContent, 0, 1, false)
      detailPrint(preview, this.state, [[template]], () => {
        if (!preview) {
          message.success('打印任务发送成功')
          this.savePrintInfo()
        }
        this.setState({ previewLoading: false })
      })
    }
  }

  render() {
    const { env, classnames: cx, translate: __, popupContainer, printers, onHide, superRole } = this.props
    const { previewLoading, showEmpty, dynamicTitle, isDynamicTitle, isDynamicSubTitle, dynamicSubTilteList, detailTableValues } = this.state
    return (
      <>
        <div className={cx('Modal-header')}>
          <div className={cx('Modal-title')}>
            {'详情打印'}
            <a
              data-tooltip={__('Dialog.close')}
              onClick={(e) => onHide(e)}
              className={cx('Modal-close')}
            >
              <CloseIcon />
            </a>
          </div>
        </div>
        <div className={cx('Modal-body')}>
          <div className='print-form-container'>
            <div className='preview-container'>
              <Spinner size="md" overlay show={previewLoading} />
              {showEmpty && <Empty description='暂无预览效果' className='preview-empty' />}
              <iframe id='detail-preview' width='100%' height='100%'></iframe>
            </div>
            <Tabs tabBarStyle={{ marginBottom: 8, paddingLeft: 24, paddingRight: 24 }} style={{ width: 350 }}>
              <Tabs.TabPane key={1} tab='设置'>
                <div className="print-setting">
                  <div className="print-setting-label">
                    打印设备
                  </div>
                  <div className="print-setting-content">
                    <Row gutter={10}>
                      <Col span={12}>
                        <Form.Item colon={false} label={__('CRUD.printer')} >
                          <Select
                            style={{ width: 170 }}
                            getPopupContainer={popupContainer}
                            dropdownClassName='label-print-selector'
                            value={this.state.printer}
                            onChange={value => this.setState({ printer: value })}
                          >
                            {printers.map(item => <Option key={item} value={item}>{item}</Option>)}
                          </Select>
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item colon={false} label={__('CRUD.pageSize')}  >
                          <Select
                            getPopupContainer={popupContainer}
                            dropdownClassName='label-print-selector'
                            value={this.state.page}
                            onChange={value => this.setState({ page: value, width: sizeOptions[value][0], height: sizeOptions[value][1] })}
                          >
                            {pageOptions.map(item => <Option key={item.value} value={item.value}>{item.label}</Option>)}
                          </Select>
                        </Form.Item>
                      </Col>
                    </Row>
                    <Row gutter={10}>
                      <Col span={12}>
                        <Form.Item colon={false} label={__('width')}  >
                          <InputNumber style={{ width: 170 }} min={0} max={1000} value={this.state.width} onChange={value => value != null && this.setState({ width: value })} />
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item colon={false} label={__('height')}  >
                          <InputNumber style={{ width: 170 }} min={0} max={1000} value={this.state.height} onChange={value => value != null && this.setState({ height: value })} />
                        </Form.Item>
                      </Col>
                    </Row>
                  </div>
                  <div className="print-setting-label">纸张设置(单位：mm)</div>
                  <div className="print-setting-content">
                    <Row gutter={10}>
                      <Col span={12}>
                        <Form.Item colon={false} label={__('up')} >
                          <InputNumber style={{ width: 120 }} min={0} max={100} value={this.state.top} onChange={value => value != null && this.setState({ top: value })} />
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item colon={false} label={__('below')} >
                          <InputNumber style={{ width: 120 }} min={0} max={100} value={this.state.bottom} onChange={value => value != null && this.setState({ bottom: value })} />
                        </Form.Item>
                      </Col>
                    </Row>
                    <Row gutter={10}>
                      <Col span={12}>
                        <Form.Item colon={false} label={__('left')} >
                          <InputNumber style={{ width: 120 }} min={0} max={100} value={this.state.left} onChange={value => value != null && this.setState({ left: value })} />
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item colon={false} label={__('right')} >
                          <InputNumber style={{ width: 120 }} min={0} max={100} value={this.state.right} onChange={value => value != null && this.setState({ right: value })} />
                        </Form.Item>
                      </Col>
                    </Row>
                    <Row>
                      <Col span={24}>
                        <Form.Item colon={false} label='双面'>
                          <Select
                            style={{ width: 160 }}
                            value={this.state.duplex}
                            options={duplexPrintOptions}
                            onChange={value => this.setState({ duplex: value })}
                          />
                        </Form.Item>
                      </Col>
                    </Row>
                    <Row >
                      <Col span={24}>
                        <Form.Item colon={false} label={__('direction')} >
                          <Radio.Group
                            value={this.state.direction}
                            onChange={value => this.setState({ direction: value.target.value })}
                          >
                            <Radio value={'vertical'}>{__('vertical')}</Radio>
                            <Radio value={'horizontal'}>{__('horizontal')}</Radio>
                          </Radio.Group>
                        </Form.Item>
                      </Col>
                    </Row>
                    {this.batchPrint && (
                      <Row>
                        <Col span={24}>
                          <Form.Item colon={false} label={'每张个数'} >
                            <InputNumber style={{ width: 130 }} min={1} max={5} value={this.state.numberOfPage} onChange={value => value != null && this.setState({ numberOfPage: value })} />
                          </Form.Item>
                        </Col>
                      </Row>
                    )}
                    <Row>
                      <Col span={24}>
                        <Form.Item colon={false} label={'打印份数'} >
                          <InputNumber style={{ width: 130 }} min={1} max={10} value={this.state.copies} onChange={value => value != null && this.setState({ copies: value })} />
                        </Form.Item>
                      </Col>
                    </Row>
                    {/* <Row>
                      <Col span={24}>
                        <Form.Item colon={false} label={__('zoom')} >
                          <InputNumber style={{ width: 160 }} step={1} min={10} max={200} value={this.state.scale} onChange={value => value != null && this.setState({ scale: value })} />
                        </Form.Item>
                      </Col>
                    </Row> */}
                  </div>
                </div>
              </Tabs.TabPane>
              <Tabs.TabPane key={2} tab='选项'>
                <div className="print-setting">
                  <div className="print-setting-label">内容设置</div>
                  <div className="print-setting-content">
                    <Row align="middle">
                      <Col span={6}>
                        <Checkbox disabled={!superRole} checked={this.state.showTitle} onChange={e => this.setState({ showTitle: e.target.checked })}>标题</Checkbox>
                      </Col>
                      <Col span={16}>
                        {isDynamicTitle ?
                          <Select
                            disabled={!superRole}
                            style={{ width: '100%' }}
                            getPopupContainer={popupContainer}
                            dropdownClassName='label-print-selector'
                            placeholder={__('Select.placeholder')}
                            value={this.state.title}
                            options={[{ label: dynamicTitle, value: dynamicTitle }]}
                          />
                          : <Input disabled={!superRole} value={this.state.title} onChange={e => this.setState({ title: e.target.value })} maxLength={50} placeholder={__('CRUD.fillIn')} />}
                      </Col>
                      <Col span={2}>
                        <Popover
                          trigger={'click'}
                          placement='bottom'
                          getPopupContainer={env.getModalContainer}
                          showArrow={false}
                          content={
                            <div style={{ display: 'flex', flexDirection: 'column' }}>
                              <span>字体</span>
                              <Select
                                disabled={!superRole}
                                style={{ width: 100 }}
                                value={this.state.titleFontFamily}
                                options={fontFamilyOptions}
                                onChange={val => this.setState({ titleFontFamily: val })}
                              />
                              <span style={{ marginTop: 4 }}>字号</span>
                              <Select
                                disabled={!superRole}
                                style={{ width: 100 }}
                                value={this.state.titleFontSize}
                                options={fontSizeOptions}
                                onChange={val => this.setState({ titleFontSize: val })}
                              />
                            </div>
                          }>
                          <FontColorsOutlined style={{ fontSize: 20, paddingLeft: 8, paddingTop: 3, color: '#00000065' }} />
                        </Popover>
                      </Col>
                    </Row>
                    <Row align="middle">
                      <Col span={6}>
                        <Checkbox disabled={!superRole} checked={this.state.showDynamicSubTitles} onChange={e => this.setState({ showDynamicSubTitles: e.target.checked })}>子标题</Checkbox>
                      </Col>
                      <Col span={16}>
                        {isDynamicSubTitle ?
                          <Select
                            disabled={!superRole}
                            style={{ width: '100%' }}
                            getPopupContainer={popupContainer}
                            dropdownClassName='label-print-selector'
                            showArrow
                            mode="multiple"
                            placeholder={__('Select.placeholder')}
                            maxTagCount='responsive'
                            value={this.state.dynamicSubTiltes}
                            onChange={value => {
                              if (value.length <= 3) {
                                this.setState({ dynamicSubTiltes: value })
                              } else {
                                env.notify('error', '最多选择3项')
                              }
                            }}
                          >
                            {dynamicSubTilteList.map((item, index) => <Option key={index} value={item}>{item}</Option>)}
                          </Select> :
                          <Input disabled={!superRole} value={this.state.subTitle} onChange={e => this.setState({ subTitle: e.target.value })} maxLength={50} placeholder={__('CRUD.fillIn')} />
                        }
                      </Col>
                      <Col span={2}>
                        <Popover
                          trigger={'click'}
                          placement='bottom'
                          getPopupContainer={env.getModalContainer}
                          showArrow={false}
                          content={
                            <div style={{ display: 'flex', flexDirection: 'column' }}>
                              <span>字体</span>
                              <Select
                                disabled={!superRole}
                                style={{ width: 100 }}
                                value={this.state.subTitleFontFamily}
                                options={fontFamilyOptions}
                                onChange={val => this.setState({ subTitleFontFamily: val })}
                              />
                              <span style={{ marginTop: 4 }}>字号</span>
                              <Select
                                disabled={!superRole}
                                style={{ width: 100 }}
                                value={this.state.subTitleFontSize}
                                options={fontSizeOptions}
                                onChange={val => this.setState({ subTitleFontSize: val })}
                              />
                            </div>
                          }>
                          <FontColorsOutlined style={{ fontSize: 20, paddingLeft: 8, paddingTop: 3, color: '#00000065' }} />
                        </Popover>
                      </Col>
                    </Row>
                    <Row align="middle">
                      <Col span={12}>
                        <Checkbox disabled={!superRole} checked={this.state.titleAllPrint} onChange={e => this.setState({ titleAllPrint: e.target.checked })}>标题每页打印</Checkbox>
                      </Col>
                      <Col span={12}>
                        <Checkbox disabled={!superRole} checked={this.state.subTitleAllPrint} onChange={e => this.setState({ subTitleAllPrint: e.target.checked })}>子标题每页打印</Checkbox>
                      </Col>
                    </Row>
                    <Divider />
                    <Row align="middle">
                      <Col span={6}>
                        <Checkbox disabled={!superRole} checked={this.state.showHeader} onChange={e => this.setState({ showHeader: e.target.checked })}>页眉</Checkbox>
                      </Col>
                      <Col span={16}>
                        <Input disabled={!superRole} value={this.state.headerTitle} onChange={e => this.setState({ headerTitle: e.target.value })} maxLength={50} placeholder={__('CRUD.fillIn')} />
                      </Col>
                      <Col span={2}>
                        <Popover
                          trigger={'click'}
                          placement='bottom'
                          getPopupContainer={env.getModalContainer}
                          showArrow={false}
                          content={
                            <div style={{ display: 'flex', flexDirection: 'column' }}>
                              <span>字体</span>
                              <Select
                                disabled={!superRole}
                                style={{ width: 100 }}
                                value={this.state.headerFontFontFamily}
                                options={fontFamilyOptions}
                                onChange={val => this.setState({ headerFontFontFamily: val })}
                              />
                              <span style={{ marginTop: 4 }}>字号</span>
                              <Select
                                disabled={!superRole}
                                style={{ width: 100 }}
                                value={this.state.headerFontSize}
                                options={fontSizeOptions}
                                onChange={val => this.setState({ headerFontSize: val })}
                              />
                            </div>
                          }>
                          <FontColorsOutlined style={{ fontSize: 20, paddingLeft: 8, paddingTop: 3, color: '#00000065' }} />
                        </Popover>
                      </Col>
                    </Row>
                    <Row align="middle">
                      <Col span={6}></Col>
                      <Col span={8}>
                        <Checkbox disabled={!superRole} checked={this.state.showHeaderLine} onChange={e => this.setState({ showHeaderLine: e.target.checked })}>页眉横线</Checkbox>
                      </Col>
                      <Col span={8}>
                        <Checkbox disabled={!superRole} checked={this.state.showLogo} onChange={e => this.setState({ showLogo: e.target.checked })}>公司Logo</Checkbox>
                      </Col>
                    </Row>
                    <Divider />
                    <Row align="middle">
                      <Col span={6}>
                        <Checkbox disabled={!superRole} checked={this.state.showFooter} onChange={e => this.setState({ showFooter: e.target.checked })}>页脚</Checkbox>
                      </Col>
                      <Col span={8}>
                        <Checkbox disabled={!superRole} checked={this.state.showPrinter} onChange={e => this.setState({ showPrinter: e.target.checked })}>打印者</Checkbox>
                      </Col>
                      <Col span={8}>
                        <Checkbox disabled={!superRole} checked={this.state.showPageNum} onChange={e => this.setState({ showPageNum: e.target.checked })}>页码</Checkbox>
                      </Col>
                      <Col span={2}>
                        <Popover
                          trigger={'click'}
                          placement='bottom'
                          getPopupContainer={env.getModalContainer}
                          showArrow={false}
                          content={
                            <div style={{ display: 'flex', flexDirection: 'column' }}>
                              <span>字体</span>
                              <Select
                                disabled={!superRole}
                                style={{ width: 100 }}
                                value={this.state.footerFontFamily}
                                options={fontFamilyOptions}
                                onChange={val => this.setState({ footerFontFamily: val })}
                              />
                              <span style={{ marginTop: 4 }}>字号</span>
                              <Select
                                disabled={!superRole}
                                style={{ width: 100 }}
                                value={this.state.footerFontSize}
                                options={fontSizeOptions}
                                onChange={val => this.setState({ footerFontSize: val })}
                              />
                            </div>
                          }>
                          <FontColorsOutlined style={{ fontSize: 20, paddingLeft: 8, paddingTop: 3, color: '#00000065' }} />
                        </Popover>
                      </Col>
                    </Row>
                    <Row align="middle" >
                      <Col span={6}></Col>
                      <Col span={8}>
                        <Checkbox disabled={!superRole} checked={this.state.showDate} onChange={e => this.setState({ showDate: e.target.checked })}>打印时间</Checkbox>
                      </Col>
                      <Col span={8}>
                        <Checkbox disabled={!superRole} checked={this.state.showFooterLine} onChange={e => this.setState({ showFooterLine: e.target.checked })}>页脚横线</Checkbox>
                      </Col>
                    </Row>
                    <Divider />
                    <Row align="middle">
                      <Col title='数字或字母强制换行' span={6}><Checkbox disabled={!superRole} checked={this.state.numberBreak} onChange={e => this.setState({ numberBreak: e.target.checked })}>换行</Checkbox></Col>
                      <Col span={8}>
                        <Checkbox disabled={!superRole} checked={this.state.showBarCode} onChange={e => {
                          const checked = e.target.checked;
                          this.setState(pre => ({ showBarCode: checked, showQRCode: checked ? false : pre.showQRCode }))
                        }}
                        >
                          打印条码
                        </Checkbox>
                      </Col>
                      <Col span={8}>
                        <Checkbox
                          disabled={!superRole}
                          checked={this.state.showQRCode}
                          onChange={e => {
                            const checked = e.target.checked
                            this.setState(pre => ({ showQRCode: checked, showBarCode: checked ? false : pre.showBarCode }))
                          }}
                        >
                          打印二维码
                        </Checkbox>
                      </Col>
                    </Row>
                  </div>
                  <div className="print-setting-label">表单样式</div>
                  <div className="print-setting-content">
                    <Row align="middle" >
                      <Col span={12}>线条宽度&nbsp;&nbsp;<InputNumber disabled={!superRole} min={1} max={4} value={this.state.lineWidth} onChange={value => { this.setState({ lineWidth: value ?? 1 }) }} /></Col>
                      <Col span={12}>边框宽度&nbsp;&nbsp;<InputNumber disabled={!superRole} min={1} max={4} value={this.state.borderWidth} onChange={value => { this.setState({ borderWidth: value ?? 1 }) }} /></Col>
                    </Row>
                    <Row align="middle" >
                      <Col span={12}>行内边距&nbsp;&nbsp;<InputNumber disabled={!superRole} min={0} max={8} value={this.state.rowPadding} onChange={value => { this.setState({ rowPadding: value ?? 1 }) }} /></Col>
                      <Col span={12}>列内边距&nbsp;&nbsp;<InputNumber disabled={!superRole} min={0} max={8} value={this.state.colPadding} onChange={value => { this.setState({ colPadding: value ?? 1 }) }} /></Col>
                    </Row>
                    <Row align="middle" >
                      <Col span={12}>表单字体&nbsp;&nbsp;
                        <Select disabled={!superRole} style={{ width: 90 }} value={this.state.contentFontFamily} options={fontFamilyOptions} onChange={value => this.setState({ contentFontFamily: value })} />
                      </Col>
                      <Col span={12}>表单字号&nbsp;&nbsp;
                        <Select disabled={!superRole} style={{ width: 90 }} value={this.state.contentFontSize} options={fontSizeOptions} onChange={value => this.setState({ contentFontSize: value })} />
                      </Col>
                    </Row>
                    <Row align='middle'>
                      <Col span={12}>标题宽度&nbsp;&nbsp;
                        <InputNumber disabled={!superRole} style={{ width: 90 }} min={10} max={50} formatter={(value) => `${value}%`} value={this.state.labelWidthPercent} onChange={value => this.setState({ labelWidthPercent: value ?? 30 })} />
                      </Col>
                    </Row>
                  </div>
                </div>
              </Tabs.TabPane>
              <Tabs.TabPane key={3} tab='数据' style={{ height: '100%' }}>
                <TableSetting superRole={superRole} detailTableValues={detailTableValues} onTableValuesChange={values => this.setState({ detailTableValues: values})} />
              </Tabs.TabPane>
            </Tabs>
          </div>
        </div>
        <div className={cx('Modal-footer')} >
          {(superRole || this.props.actionType === 'flow-print') && <Button onClick={() => this.handleDeleteSetting()}>清空默认值</Button>}
          {(superRole || this.props.actionType === 'flow-print') && <Button onClick={() => this.handleSaveSetting()} loading={this.state.saveLoading}>设置默认值</Button>}
          <Button level="primary" onClick={this.handleDetailPrint.bind(this, true)} >{__('preview')}</Button>
          <Button level="primary" onClick={this.handleDetailPrint.bind(this, false)} >{__('print')}</Button>
          <Button onClick={(e: any) => onHide(e)}>{__('cancel')}</Button>
        </div >
      </>
    )
  }
}

