<template>
  <div class="design-container" style="height: 850px;">
    <div id='box' class='flex'>
      <!-- <div id='left' class='w-1/2 bg-gray-200' v-loading="loading" style="position: relative;"> -->
      <div id='left' v-loading="loading" style="position: relative; width: 50%;">
        <el-card :style='{ "height": cardHeight, "shadow": "never" }' class="card-body">
          <el-scrollbar :height='scrollbarHeight'>
            <div id="form-info">
              <!-- 表单信息 -->
              <div class="pdf-item">
                <h2 class="title header">{{ formTitle }}</h2>
              </div>
              <FormDesign ref="form" :columnConfig="columnConfig" v-model:data="formData" :viewerMode="viewerMode"
                @preview='handleOpenRightScreen'>
                <template #top>
                  <div class="pdf-item">
                    <GdInput :label="$t('applyID')" prop="i_apply_id" disabled :viewerMode="viewerMode"
                      v-if="formData.i_apply_id" />
                  </div>
                </template>
              </FormDesign>
              <div class="pdf-item" style="height: 50px;"></div>

              <!-- 阅览人 -->
              <div class="pdf-item">
                <h2 class="title header">{{ $t('notice_readers') }}</h2>
                <el-form :class="{ 'design-form': true, 'viewer-mode': !notifiable && viewerMode }" :model="formData"
                  label-width="200px" :label-position="!notifiable && viewerMode ? 'left' : 'top'" style="min-height:0">
                  <GdTableSelect :label="$t('notice_readers_label')" :hideLabel="!(!notifiable && viewerMode)"
                    prop="i_notice_readers" type="user" multiple class="readable-user" :collapse-tags="false"
                    :viewerMode="!notifiable && viewerMode" />
                </el-form>
              </div>


              <div v-if="auditData.node?.length > 1" class="pdf-item" style="height: 50px;"></div>

              <!-- 审批履历 -->
              <template v-if="auditData.node?.length > 1">
                <div class="pdf-item">
                  <h2 class="title header">{{ $t('aduit_his') }}</h2>
                </div>
                <div v-for="(item, index) in auditData.node">
                  <div class="pdf-item" style="height:10px"></div>
                  <AuditNode class="pdf-item" :key="index" :nodeData="item" :index="index + 1"
                    :latestVersion="auditData.node[auditData.node.length - 1].i_submit_times" :notifiable="notifiable"
                    @communicate="handleCommunicate" />
                </div>
              </template>
            </div>
          </el-scrollbar>
          <div class="footer" ref="footer">
            <template v-if="modifiable && [undefined, AuditStatus.DRAFT, AuditStatus.REJECTED].includes(formData.i_status)">
              <el-button @click="previewVisible = true" :disabled="loading">
                {{ $t('approvalFlow') }}
              </el-button>
              <el-button @click="handleSave(false)" :disabled="loading">
                {{ $t('save') }}
              </el-button>
              <el-button @click="handleSave(true)" :disabled="loading" type="primary">
                {{ $t('submit') }}
              </el-button>
            </template>
            <template v-if="isAudit && [AuditStatus.AUDITING].includes(formData.i_status)">
              <el-form :model="data">
                <GdInput type="textarea" :label="$t('opinions')" prop="i_comment" style="margin-bottom: 3px;" />
              </el-form>
              <el-button type="success" @click="handleAudit('2')" :disabled="loading">
                {{ $t('approve') }}
              </el-button>
              <el-button type="danger" @click="handleAudit('3')" :disabled="loading">
                {{ $t('reject') }}
              </el-button>
            </template>
            <el-button type="primary" plain v-if="notifiable" @click="handleNotify" :disabled="loading">
              {{ $t('notify') }}
            </el-button>
            <el-button type="primary" plain @click="handlePrintPDF" :disabled="loading">{{ $t('print_pdf') }}</el-button>
          </div>
        </el-card>
      </div>
      <div id='resize' class='border cursor-col-resize'></div>
      <!-- <div id='mid' class='w-1/2 bg-gray-200' style="overflow: hidden;"> -->
      <div id='mid' style="overflow: hidden; width: 50%;">
        <div v-if='url' class='flex justify-end text-white' @click="handleOpenRightScreen('')">
          <close-small fill='#ffffff' size='24' theme='outline' />
        </div>
        <el-scrollbar :height='auxiliaryHeight' v-loading="previewLoading" style="overflow: hidden;">
          <div style='min-width: 48rem;height: 100%;'>
            <vue-pdf v-if='pdfShow === true' :src='url' allPages @pdfLoaded="previewLoading = false"></vue-pdf>
            <el-image v-else :src='url' fit='contain' style='width: 100%;' @load="previewLoading = false"
              @error="previewLoading = false" />
          </div>
        </el-scrollbar>
      </div>
    </div>
  </div>
  <el-dialog :title="$t('approvalFlow')" v-model="previewVisible" destroy-on-close
    style="margin-top: 30px !important;margin-bottom: 0px !important;">
    <Config />
  </el-dialog>
  <el-dialog :title="$t('contact')" v-model="messageFormVisible" destroy-on-close>
    <el-form ref="messageForm" class="gd-form" :model="messageFormData" label-width="120px" v-loading="messageLoading">
      <GdSelect prop="i_contact_user" :label="$t('contact_member')" :options="contactUserList" required />
      <GdInput type="textarea" prop="i_comment" :label="$t('contact_message')" required />
      <GdUpload prop="i_files" :label="$t('contact_attach')" :previewable="false" />
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleSendMessage" :disabled="messageLoading">
          {{ $t("contact_send") }}
        </el-button>
        <el-button @click="messageFormVisible = false">{{ $t("dialogClose") }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { CloseSmall } from '@icon-park/vue-next';
import { reactive, ref, computed, getCurrentInstance, onActivated, onMounted, provide, nextTick, popScopeId } from 'vue'
import FormDesign from '@/views/workflowManagement/workflow/components/formDesign.vue';
import { getDetail, saveApply, modifyApply, getMyDetail, Audit, IAudit, INoticeReferenceUser, noticeReferenceUser, sendMessage, uploadFile } from '@/api/workflowManagement'
import { useGlobalPinia } from '@/pinia/global';
import { useWindowSize, useElementBounding } from '@vueuse/core';
import { useRouter, useRoute } from 'vue-router';
import { FormInstance } from 'element-plus';
// import { useRoutesStore } from '@/pinia/permission'
import { replace } from '@/utils/index';
import AuditNode from './auditNode.vue';
import htmlToPdf from '@/utils/pdf'
import { AuditStatus } from '@/model/enums'
import key from '@/constant/key';
import Cookies from 'js-cookie';
import moment from 'moment';
import { getDatePattern } from '@/components/GdElement/common';
import Config from '@/views/workflowManagement/workflow/components/audit/config.vue'
import jsPDF from 'jspdf';
import { ElMessage, ElMessageBox } from 'element-plus'
import useTagsViewStore from '@/store/modules/tagsView'

// const { VITE_BASE_URL } = import.meta.env
const { VITE_APP_BASE_API } = import.meta.env
const $t: any = getCurrentInstance()?.appContext.config.globalProperties.$t

// const routesStore = useRoutesStore()
// const currentRoute = useRoute();
const router = useRouter()
const windowSize = useWindowSize();
const global = useGlobalPinia();
const footer = ref()
const footerHeight = useElementBounding(footer)
// const cardHeight = computed(() => windowSize.height.value - global.header - global.mainPadding + 'px');
const cardHeight = computed(() => windowSize.height.value - global.header - global.mainPadding + 'px');
const auxiliaryHeight = computed(() => windowSize.height.value - global.header - global.mainPadding - 24 - 24 + 'px');
// const scrollbarHeight = computed(() => windowSize.height.value - global.mainPadding - footerHeight.height.value - 120 + 'px');
const scrollbarHeight = computed(() => windowSize.height.value - global.mainPadding - footerHeight.height.value - 90 + 'px');
const currentTag = router.currentRoute.value

const props = withDefaults(defineProps<{
  formId: any,
  dataId?: any,
  viewerMode?: boolean,
  isAudit?: boolean,
  isCopy?: boolean,
  modifiable?: boolean,
  notifiable?: boolean
}>(), {})

const data: any = reactive({})
const formData: any = reactive({})
const auditData: any = reactive({})
const auditConfig = ref({})
const columnConfig = ref([])
const formTitle = ref('')
const currentFormId = ref()
const loading = ref(false)
const state: any = reactive({ disabled: true })
const evidenceFolder = ref('')
const tempFileFolder = ref('')
provide('state', state)
provide('previewable', true)

let login_user = ''
// const is_applyer = computed(() => !formData.i_apply_id || (formData.i_apply_user === Cookies.get(key.user)))
const is_applyer = computed(() => !formData.i_apply_id || (formData.i_apply_user === login_user))
const notifiable = computed(() => props.notifiable && is_applyer.value && [AuditStatus.AUDITING].includes(formData.i_status))

onActivated(async () => {
  const { formId, dataId } = props

  // if (!formId || (formId === currentFormId.value) || (dataId && dataId === formData.i_apply_id)) return
  if ((!formId || (formId === currentFormId.value)) && (!dataId || (dataId === formData.i_apply_id))) return
  loading.value = true

  // 清空历史数据
  replace(data, {})
  replace(formData, {})
  replace(auditData, {})
  columnConfig.value = []
  handleOpenRightScreen('')
  login_user = ''

  try {
    await Promise.all([
      // 1. 初始化表单项
      getDetail(formId).then(({ data }) => {
        formTitle.value = data.title
        currentFormId.value = data.i_form_id
        columnConfig.value = JSON.parse(data.columnConfig)
        auditConfig.value = JSON.parse(data.auditConfig)
        state.formConfig = { columnConfig: columnConfig.value, auditConfig: auditConfig.value }
        evidenceFolder.value = data.evidenceFolder
        tempFileFolder.value = data.tempFileFolder
        // 为upload组件传递表单ID及申请ID
        columnConfig.value.forEach((item: any) => {
          if (item.control === 'upload') {
            item.formId = data.i_form_id
            item.i_apply_id = props.isCopy ? undefined : dataId
          }
        })
        // 1.1 新增时默认值设置
        if (!dataId) {
          columnConfig.value.forEach((item: any) => {
            if (item.control === 'date-picker' && item.systemDate) {
              const now = moment().format(getDatePattern(null))
              item.defaultPropValue = item.type.includes('range') ? `${now},$${now}` : now
            }
            if (item.control === 'switch') {
              item.defaultPropValue = item.defaultPropValue || false
            }
            if (item.defaultPropValue !== undefined) {
              formData[item.prop] = item.defaultPropValue
            }
          })
        }
      }),
      // 2. 获取业务数据
      // dataId ? getMyDetail(dataId, props.isCopy ? true : false).then(({ data }) => {
      //   if (props.isCopy) {
      //     data.data.i_pre_appl_id = dataId
      //     data.data.i_apply_id = undefined
      //     data.data.i_status = undefined
      //     data.flow = {}
      //   }
      //   replace(formData, data.data)
      //   replace(auditData, data.flow)
      // }) : Promise.resolve()
      dataId ? getMyDetail(dataId, props.isCopy ? true : false).then(res => {
        if (props.isCopy) {
          res.data.data.i_pre_appl_id = dataId
          res.data.data.i_apply_id = undefined
          res.data.data.i_status = undefined
          res.data.flow = {}
        }
        login_user = (res as any).login_user
        replace(formData, res.data.data)
        replace(auditData, res.data.flow)
      }) : Promise.resolve()
    ])
  } finally {
    loading.value = false
  }
})

onMounted(() => {
  dragControllerDiv()
})

const previewVisible = ref(false)

const form = ref<FormInstance>()
const handleSave = async (isSubmit: boolean) => {
  try {
    await form.value?.validate()
  } catch (e) {
    console.error(e);
    ElMessage.warning($t('form_check_rejected'))
    return
  }

  if (isSubmit) {
    try {
      await ElMessageBox.confirm(
        `${$t('confirmSubmit')}`,
      )
    } catch (e) {
      console.error(e);
      return
    }
  }

  loading.value = true
  try {
    const params = formData
    params.formId = props.formId
    params.isSubmit = isSubmit
    const action = params.i_apply_id ? modifyApply : saveApply
    const { resultCode }: any = await action(params)
    if (resultCode === '0') {
      ElMessage.success($t(isSubmit ? 'common_0120' : 'common_0090'))
      // routesStore.closeTag(currentRoute.name)
      // router.push({ name: 'WFApplyListMy' })
      router.push({path:'myApply'})
      useTagsViewStore().delView(currentTag)
    }
  } catch (error) {
    console.error(error);
  } finally {
    loading.value = false
  }
}

const handleNotify = async () => {
  try {
    await ElMessageBox.confirm(
      `${$t('confirmNotice')}`,
    )
  } catch (e) {
    console.error(e);
    return
  }

  loading.value = true
  const params: INoticeReferenceUser = {
    i_apply_id: formData.i_apply_id,
    i_notice_readers: formData.i_notice_readers
  }
  try {
    const { resultCode }: any = await noticeReferenceUser(params)
    if (resultCode === '0') {
      ElMessage.success($t('common_0060'))
    }
  } finally {
    loading.value = false
  }
}

const handleAudit = async (i_audit_result: string) => {
  const isReject = i_audit_result === '3'
  if (isReject && (!data.i_comment || data.i_comment.trim() === '')) {
    ElMessage.warning($t('common_0212'))
    return
  }
  try {
    await ElMessageBox.confirm(
      `${$t(isReject ? 'confirmReject' : 'confirmApprove')}`,
    )
  } catch (e) {
    console.error(e);
    return
  }
  loading.value = true
  const params: IAudit = {
    i_apply_id: formData.i_apply_id,
    i_audit_result,
    i_comment: data.i_comment
  }
  try {
    const { applyPass }: any = await Audit(params)
    if (applyPass) {
      // 上传审批履历快照
      const { data } = await getMyDetail(props.dataId, false)
      replace(formData, data.data)
      replace(auditData, data.flow)

      nextTick(() => {
        setTimeout(() => {
          htmlToPdf.getImg('form-info', (pdf: jsPDF) => {
            const uploadData = new FormData()
            // uploadData.append('i_language', localStorage.getItem(key.languageKey))
            // uploadData.append('login_user', Cookies.get(key.user))
            uploadData.append('i_language', localStorage.getItem(key.languageKey) || "")
            uploadData.append('login_user', Cookies.get(key.user) || "")
            uploadData.append('i_form_id', props.formId)
            uploadData.append('i_apply_id', props.dataId)
            uploadData.append('applyPass', 'true')
            uploadData.append('file', new File([pdf.output("blob")], `${props.dataId}.pdf`))
            uploadFile(uploadData)
            ElMessage.success($t('common_0060'))
            // routesStore.closeTag(currentRoute.name)
            // router.push({ name: 'WFApplyListAudit' })
            router.push({path:'wfApplyListAudit'})
            useTagsViewStore().delView(currentTag)  
          })
        }, 1000)
      })
    } else {
      ElMessage.success($t('common_0060'))
      // routesStore.closeTag(currentRoute.name)
      // router.push({ name: 'WFApplyListAudit' })
      router.push({path:'wfApplyListAudit'})
      useTagsViewStore().delView(currentTag)
    }
  } finally {
    loading.value = false
  }

}

const handlePrintPDF = () => {
  htmlToPdf.getImg('form-info', (pdf: jsPDF) => pdf.save(`${formTitle.value}.pdf`))
}

const pdfShow = ref(false);
const previewLoading = ref(false)
const url = ref('');
const currentFile = ref('');
provide("currentFile", currentFile)

const handleOpenRightScreen = (name: string) => {
  currentFile.value = name
  if (!name) {
    url.value = ''
    previewLoading.value = false
    return
  }
  previewLoading.value = true
  const isPdf = '.pdf' === name.slice(name.lastIndexOf('.'))
  pdfShow.value = isPdf
  // url.value = `${VITE_BASE_URL}/${props.dataId ? `${evidenceFolder.value}/${props.formId}_${props.dataId}` : `${tempFileFolder.value}`}/${name}`
  if (props.isCopy) {
    url.value = `${VITE_APP_BASE_API}/profile/IWorkflow/${tempFileFolder.value}/${name}`
  } else {
    url.value = `${VITE_APP_BASE_API}/profile/IWorkflow/${props.dataId ? `${evidenceFolder.value}/${props.formId}_${props.dataId}` : `${tempFileFolder.value}`}/${name}`
  }
};


const dragControllerDiv = function () {
  var resize: any = document.getElementById('resize');
  var left: any = document.getElementById('left');
  var mid: any = document.getElementById('mid');
  var box: any = document.getElementById('box');

  if (resize) {
    // 鼠标按下事件
    resize.onmousedown = function (e: any) {
      if (resize) {
        //颜色改变提醒
        resize.style.background = '#818181';
        var startX = e.clientX;
        resize.left = resize.offsetLeft;
      }
      // 鼠标拖动事件
      document.onmousemove = function (e) {
        var endX = e.clientX;
        var moveLen = resize.left + (endX - startX); // （endx-startx）=移动的距离。resize[i].left+移动的距离=左边区域最后的宽度
        var maxT = box.clientWidth - resize.offsetWidth; // 容器宽度 - 左边区域的宽度 = 右边区域的宽度

        if (moveLen < 32) moveLen = 32; // 左边区域的最小宽度为32px
        if (moveLen > maxT - 150) moveLen = maxT - 150; //右边区域最小宽度为150px

        resize.style.left = moveLen; // 设置左侧区域的宽度


        left.style.width = moveLen + 'px';
        mid.style.width = (box.clientWidth - moveLen - 10) + 'px';
      };
      // 鼠标松开事件
      document.onmouseup = function (evt) {
        //颜色恢复
        resize.style.background = '#d6d6d6';
        document.onmousemove = null;
        document.onmouseup = null;
        resize.releaseCapture && resize.releaseCapture(); //当你不在需要继续获得鼠标消息就要应该调用ReleaseCapture()释放掉
      };
      resize.setCapture && resize.setCapture(); //该函数在属于当前线程的指定窗口里设置鼠标捕获
      return false;
    };
  }
};


// 消息通知
const messageFormVisible = ref(false)
const messageFormData: any = reactive({})
const messageLoading = ref(false)
const contactUserList = ref([])
const handleCommunicate = (nodeData: any) => {
  contactUserList.value = nodeData.subnode
    .flatMap((item: any) => item.user)
    .map(({ i_user_id, i_proxy_user_id, i_user_name }: any) => ({ label: i_user_name, value: i_proxy_user_id ? `${i_user_id},${i_proxy_user_id}` : i_user_id }))
  messageFormData.i_apply_id = props.dataId
  messageFormData.i_contact_user = ''
  messageFormData.i_comment = ''
  messageFormData.i_files = ''
  messageFormVisible.value = true
}
const messageForm = ref<FormInstance>()
const handleSendMessage = async () => {

  try {
    await messageForm.value?.validate()
  } catch (e) {
    console.error(e);
    ElMessage.warning($t('form_check_rejected'))
    return
  }

  messageLoading.value = true
  try {
    const params = messageFormData
    const { resultCode, errorDesc }: any = await sendMessage(params)
    if (resultCode === '0') {
      ElMessage.success(errorDesc)
      messageFormVisible.value = false
    }
  } catch (error) {
    console.error(error);
  } finally {
    messageLoading.value = false
  }
}
</script>

<style lang="scss">
#form-info .title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 20px;
  color: #000000;
  line-height: 25px;
}

#form-info .title.header {
  border-bottom: 1px solid #6365E7;
  padding-bottom: 10px;
}

.card-body .el-card__body {
  padding: 0;
}

#form-info {
  padding: 20px;
}

.footer {
  text-align: right;
  // padding: 0 30px;
  padding: 20px;
  // position: absolute;
  // bottom: 10px;
  width: 100%;
}

.readable-user .el-select {
  width: 100%;
}

.pdf-item {
  border: 1px solid transparent;
}

#mid .el-loading-mask {
  z-index: 1;
}

.flex {
  display: flex;
  width: 100%;
}

.border {
  border-width: 1px;
}

.cursor-col-resize {
  cursor: col-resize;
}

.justify-end {
  justify-content: flex-end;
}

.text-white {
  background:gainsboro;
}
</style>