<script setup lang="ts">
import SignatureComponent from '@af-mobile-client-vue3/components/core/Signature/SignatureComponent.vue'
import XSelect from '@af-mobile-client-vue3/components/core/XSelect/index.vue'
import FilePreview from '@af-mobile-client-vue3/components/data/FilePreview/index.vue'
import XForm from '@af-mobile-client-vue3/components/data/XForm/index.vue'
import { getConfigByName, runLogic } from '@af-mobile-client-vue3/services/api/common'
import { useUserStore } from '@af-mobile-client-vue3/stores/modules/user'
import { showToast, Button as VanButton, CellGroup as VanCellGroup, Dialog as VanDialog, Loading as VanLoading } from 'vant'
import { computed, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'

/** 生成合同接口返回的 data 结构 */
interface ContractDetail {
  f_signature_url?: string
  f_signature_path?: string
  f_contract_signature_id?: string
  f_contract_type?: string
  [key: string]: unknown
}

interface GenerateContractResponse {
  data: ContractDetail
}

const route = useRoute()
// 获取当前登录用户信息
const userInfo = useUserStore().getUserInfo()
// 获取操作员信息
const currUser = useUserStore().getLogin().f
const workflowId = computed(() => route.query.workflowId?.toString() || '')
const userId = computed(() => route.query.userId?.toString() || '')
// 合同名称
const f_contract_name = ref('')
// 表单名称
const configName = ref('')
// 展示合同表单
const contractshow = ref(false)
// 合同选择类型
const contracttypes = ref<any[]>([])
// 合同模板
const contractTemplate = ref<any[]>([])
// 用户信息
const userRecord = ref<any[]>([])
// 合同的表单数据
const formData = ref({})
// 合同表单引用
const contractFormRef = ref()
// 显示pdf
const preview = ref(false)
// pdf的路径
const previewPath = ref('')
// pdf查看组件引用
const filePreviewRef = ref()
// 显示签字弹窗
const previewVisible = ref(false)
// 签字组件引用
const signatureRef = ref<any>()
// 生成的合同信息
const contractdetails = ref<ContractDetail>({})
const status = ref(false)

function contractconfirm() {
  if (f_contract_name.value !== '') {
    contractshow.value = true
    configName.value = `${f_contract_name.value}Form`
    getConfigByName(configName.value, (config) => {
      if (config !== null && config !== undefined) {
        contractFormRef.value.init(config)
      }
      else {
        contractshow.value = false
      }
    }, 'af-system')
  }
  else {
    contractshow.value = false
  }
}
function contractsubmit(res) {
  Object.assign(formData.value, res)
  const contractInfo = {
    f_process_id: workflowId.value,
  }
  contractTemplate.value.forEach((item) => {
    if (item?.f_contract_name === f_contract_name.value) {
      Object.assign(contractInfo, item)
    }
  })
  const resData = {
    contractInfo,
    loginInfo: {
      f_operatorid: userInfo.f_operatorid || currUser.resources.id,
      f_operator: userInfo.f_operator || currUser.resources.name,
      f_orgid: userInfo.f_orgid || currUser.resources.orgid,
    },
    userRecord: userRecord.value[0],
    formData: res,
  }
  preview.value = true
  status.value = true
  runLogic('generateContract', resData, 'af-revenue').then((contract: GenerateContractResponse) => {
    showToast('生成合同成功!')
    console.log('contract', contract)
    contractdetails.value = contract.data
    const path = contract.data.f_signature_url
    filePreviewRef.value.init({ path })
    status.value = false
  })
}
function goBack() {
  preview.value = false
}
function openSign() {
  previewVisible.value = true
}
function onDialogCancel() {
  previewVisible.value = false
}
async function onSignSubmit() {
  const signData = await Promise.resolve(signatureRef.value?.getSignatureData?.())
  console.log('signData', signData)
  let f_signature_location = ''
  contractTemplate.value.forEach((item) => {
    if (item?.f_contract_name === f_contract_name.value) {
      f_signature_location = item.f_signature_location
    }
  })
  const resData = {
    f_signature_path: contractdetails.value.f_signature_path,
    f_contract_url: contractdetails.value.f_signature_url,
    f_contract_signature_id: contractdetails.value.f_contract_signature_id,
    f_signature_location,
    f_contract_type: contractdetails.value.f_contract_type,
    image: signData,
  }
  runLogic('contractSignature', resData, 'af-revenue').then(() => {
    showToast('合同签字成功!')
    preview.value = false
    history.back()
  })
}

onMounted(() => {
  runLogic('getUserinfoByid', {
    condition: ` ui.f_userinfo_id = '${userId.value}' `,
  }, 'af-system').then((row: any) => {
    if (row.length > 0) {
      userRecord.value = row
    }
    else {
      showToast('未找到用户信息!')
      return
    }
    runLogic('getContractTemplateByWorkflow', {
      f_orgid: userInfo.f_orgid || currUser.resources.orgid,
      f_userinfo_code: userRecord.value[0].f_userinfo_code,
      workflowId: workflowId.value,
    }, 'af-system').then((res: any) => {
      contracttypes.value = []
      contractTemplate.value = res
      res.forEach((item: any) => {
        contracttypes.value.push({
          label: item.f_contract_name,
          value: item.f_contract_name,
        })
      })
    })
  })
})
</script>

<template>
  <div v-if="status" style="display: flex; justify-content: center; align-items: center; height: 100vh;">
    <VanLoading vertical size="50">
      努力加载中...
    </VanLoading>
  </div>
  <div v-show="!status" class="contract-container">
    <VanCellGroup v-if="!preview" class="contract-form-group">
      <XSelect
        v-model="f_contract_name"
        :columns="contracttypes"
        label="合同名称"
        placeholder="请选择合同名称"
        @confirm="contractconfirm"
      />
      <XForm
        v-if="contractshow"
        ref="contractFormRef"
        class="contract-form"
        mode="新增"
        :form-data="formData"
        :config-name="configName"
        service-name="af-telephone"
        show-tab-header="false"
        :submit-button="true"
        @on-submit="contractsubmit"
      />
    </VanCellGroup>
    <div v-if="preview">
      <FilePreview
        ref="filePreviewRef"
        :key="`pdf-${previewPath}`"
        style="height: 95vh"
      />
      <div class="bottom-bar">
        <VanButton type="default" block @click="goBack">
          返回
        </VanButton>
        <VanButton type="primary" block @click="openSign">
          签字提交
        </VanButton>
      </div>
    </div>
    <VanDialog
      v-model:show="previewVisible"
      title="合同信息"
      show-cancel-button
      show-confirm-button
      style="max-width: 90vw; max-height: 40vh;"
      @confirm="onSignSubmit"
      @cancel="onDialogCancel"
    >
      <SignatureComponent ref="signatureRef" style="padding: 20px;" label="用户签字" :form-readonly="false" />
    </VanDialog>
  </div>
</template>

<style scoped lang="less">
.contract-container {
  height: 95vh;
  display: flex;
  flex-direction: column;
}

:deep(.contract-form-group) {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

:deep(.contract-form) {
  flex: 1;
  overflow: auto;
}

.bottom-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  padding: 8px 12px calc(8px + env(safe-area-inset-bottom));
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.06);
  z-index: 100;
}
</style>
