import UploadFile from '@/components/upload-file'
import { protocolTypeArray } from '@/utils/searchArray'
import { NForm, NFormItem, NInput, NSelect, NButton, NSpace, NModal, useMessage } from 'naive-ui'
import { defineComponent, PropType, reactive, ref } from 'vue'
import { schoolContractTemplateSave } from '../api'

export default defineComponent({
  name: 'add-protocol',
  props: {
    type: {
      type: String,
      default: 'add'
    },
    data: {
      type: Object as PropType<any>,
      default: () => {}
    }
  },
  emits: ['close', 'getList'],
  setup(props, { slots, attrs, emit }) {
    const message = useMessage()
    const visiable = ref<boolean>(false)
    const forms = reactive({
      name: '',
      type: null,
      contractNo: null,
      origanalFileUrl: null,
      contractTemplateContent: null,
      status: false,
      timeFlag: null,
      time: null
    })
    const formsRef = ref()

    const onSubmit = () => {
      formsRef.value.validate(async (error: any) => {
        if (error) return false

        try {
          await schoolContractTemplateSave({ ...forms, id: props.data.id })
          message.success('添加成功')
          emit('getList')
          emit('close')
        } catch {}
      })
    }

    const displayResult = (result: any) => {
      let html = result.value
      let newHTML = html
        .replace(//g, '')
        .replace('<h1>', '<h2 style="font-size: 16px;font-weight: bold; padding-top: 15px;">')
      forms.contractTemplateContent = newHTML
    }

    const readFileInputEventAsArrayBuffer = (file: any) => {
      let reader = new FileReader()
      reader.onload = function (loadEvent: any) {
        let arrayBuffer = loadEvent.target.result //arrayBuffer
        // @ts-ignore
        mammoth
          .convertToHtml({ arrayBuffer: arrayBuffer })
          .then(function (result: any) {
            displayResult(result)
          })
          .catch(function (e: any) {
            forms.origanalFileUrl = null
            message.error('上传文件有误，请重新上传')
          })
          .done()
      }
      reader.readAsArrayBuffer(file)
    }

    // 只能输入数字
    const onlyAllowNumber = (value: string) =>
      !value || /^(?:0.\d{0,3}|[0-9][0-9]{0,12}|[0-9]{1,10}.\d{0,3})$/.test(value)
    return () => (
      <div style="background: #fff; padding-top: 12px">
        <NForm model={forms} ref={formsRef} label-placement="left" label-width="110px">
          <NFormItem
            label="协议名称"
            path="name"
            rule={[
              {
                required: true,
                message: '请输入协议名称'
              }
            ]}
          >
            <NInput placeholder="请输入协议名称" v-model:value={forms.name} />
          </NFormItem>
          <NFormItem
            label="协议类型"
            path="type"
            rule={[
              {
                required: true,
                message: '请选择协议类型'
              }
            ]}
          >
            <NSelect
              placeholder="请选择协议类型"
              options={protocolTypeArray}
              v-model:value={forms.type}
            ></NSelect>
          </NFormItem>
          <NFormItem
            label="协议号"
            path="contractNo"
            rule={[
              {
                required: true,
                message: '请输入协议号'
              }
            ]}
          >
            <NInput placeholder="请输入协议号" v-model:value={forms.contractNo} />
          </NFormItem>
          <NFormItem
            label="签署时长状态"
            path="timeFlag"
            rule={[
              {
                required: true,
                message: '请输入签署时长状态'
              }
            ]}
          >
            <NSelect
              placeholder="请选择签署时长"
              options={
                [
                  { label: '显示', value: true },
                  { label: '隐藏', value: false }
                ] as any
              }
              v-model:value={forms.timeFlag}
            ></NSelect>
          </NFormItem>
          {/* 显示才要输入时长 */}
          {forms.timeFlag && (
            <NFormItem
              label="签署时长"
              path="time"
              rule={[
                {
                  required: true,
                  message: '请输入签署时长'
                }
              ]}
            >
              <NInput
                placeholder="请输入签署时长(年)"
                v-model:value={forms.time}
                allowInput={onlyAllowNumber}
                maxlength={2}
              />
            </NFormItem>
          )}
          <NFormItem
            label="上传协议"
            path="origanalFileUrl"
            rule={[
              {
                required: true,
                message: '请上传协议'
              }
            ]}
          >
            <UploadFile
              size={5}
              listType="image"
              tips="仅支持上传 docx 格式文件"
              accept=".docx"
              v-model:fileList={forms.origanalFileUrl}
              onReadFileInputEventAsArrayBuffer={readFileInputEventAsArrayBuffer}
              onRemove={() => {
                forms.contractTemplateContent = null
              }}
            />
          </NFormItem>
        </NForm>

        <NSpace justify="end">
          <NButton type="default" onClick={() => emit('close')}>
            取消
          </NButton>
          <NButton
            type="primary"
            onClick={() => {
              formsRef.value.validate(async (error: any) => {
                if (error) return false
                visiable.value = true
              })
            }}
          >
            下一步
          </NButton>
        </NSpace>

        <NModal
          v-model:show={visiable.value}
          preset="dialog"
          showIcon={false}
          title="查看协议"
          style={{ width: '400px' }}
        >
          <div
            style="max-height: 450px; overflow-y: auto;"
            v-html={forms.contractTemplateContent}
          ></div>
          <NSpace justify="end" style="padding-top: 16px">
            <NButton type="default" onClick={() => (visiable.value = false)}>
              取消
            </NButton>
            <NButton type="primary" onClick={onSubmit}>
              确定
            </NButton>
          </NSpace>
        </NModal>
      </div>
    )
  }
})
