<template>
  <a-modal
    v-if="visible"
    v-model="visible"
    :title="formData.pageTitle"
    destroy-on-close
    v-bind="{ width: 800 }"
    :mask-closable="false"
  >
    <sd-form
      v-if="formData.pageFormData"
      ref="form"
      :init-values="formData.pageFormData.pageFieldInfos"
    >
      <template v-slot="{ model }">
        <!-- 当用户无签名时打开新建详情签名窗口：需要将当前用户的相关信息带过来，通过默认值处理如下 -->
        <sd-form-item :hidden="true" name="userId" :input-props="{ defaultValue: user.id }" />
        <sd-form-item
          :hidden="true"
          name="userAccount"
          :input-props="{ defaultValue: user.account }"
        />
        <sd-form-item name="userName" :input-props="{ defaultValue: user.name, disabled: true }" />
        <sd-form-item name="signAttach">
          <template v-slot:read-and-edit>
            <sd-signature-upload
              :group-id="recordId || ''"
              :selected-keys="model.useSign ? model.useSign.split() : []"
              @update:selectedKeys="(data) => handleEnabledSignData(data, model)"
              @change="signAttachChange"
              @input="signAttachInput"
            />
          </template>
        </sd-form-item>
      </template>
    </sd-form>
    <template slot="footer">
      <sd-form-buttons :buttons="btns" reverse-btns @btnClick="btnClick" />
    </template>
  </a-modal>
</template>

<script>
import axios from '@/common/services/axios-instance'
import sdFormButtons from '@/common/components/sd-form/sd-form-buttons'
import components from './_import-components/sd-user-info-import'

export default {
  name: 'SdUserInfo',
  components: {
    ...components,
    sdFormButtons,
  },
  props: {
    recordId: {
      type: [String, Number],
      default: undefined,
    },
    pageId: {
      type: String,
      required: true,
    },
    user: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      visible: false,
      formData: {},
      attachments: null,
    }
  },
  computed: {
    btns() {
      return this.formData?.operationButtons?.length > 0
        ? this.formData.operationButtons
        : [{ buttonId: 'close', buttonName: '退出' }]
    },
  },
  methods: {
    show() {
      this.getData().then(() => {
        this.visible = true
      })
    },
    getData() {
      this.formData = {}
      return axios({
        url: 'api/framework/v1/page/wp/' + this.pageId,
        method: 'get',
        params: {
          id: this.recordId,
        },
      }).then((res) => {
        this.formData = res.data
      })
    },
    btnClick(evt, btn) {
      switch (btn.buttonId) {
        case 'save':
          return this.saveBtnClick()
        case 'close':
          this.visible = false
          break
        default:
          break
      }
    },
    saveBtnClick() {
      return this.$refs.form.validateFields().then(() => {
        const formData = {}
        this.$refs.form.getBackendValues().forEach((f) => {
          formData[f.name] = f.value
        })
        formData.imageIds = this.attachments.map((item) => item.code)
        return axios({
          url: 'api/framework/v1/user-signature/info',
          method: 'post',
          data: formData,
        }).then((res) => {
          if (res.status === 200) {
            this.visible = false
            this.$emit('saved')
          }
        })
      })
    },
    handleEnabledSignData(data, model) {
      if (data.length > 0) {
        model.useSign = data.slice(-1)[0]
      } else {
        model.useSign = ''
      }
    },
    signAttachChange(attachments) {
      // 判断附件是否有新增
      if (attachments.length > (this.attachments?.length || -1)) {
        // 当前为添加附件，则将最后一个附件设置为选中状态
        this.$refs.form.setFieldValue('useSign', attachments[attachments.length - 1].code)
      }
      // 更新附件
      this.attachments = [...attachments]
    },
    signAttachInput(attachments) {
      // 初始化附件数
      if (!this.attachments) {
        // 附件未初始化
        this.attachments = [...attachments]
      }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
</style>
