<script setup lang="ts" name="detail">
import { ref, reactive, computed, onMounted, onUnmounted, nextTick, defineAsyncComponent } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import AttendanceLeaveDetailFlowClose from './modules/attendance/leave/modules/DetailFlowClose.vue'
import AttendanceTripDetailFlowClose from './modules/attendance/trip/modules/DetailFlowClose.vue'
import AttendanceLeaveDetailFlow from './modules/attendance/leave/modules/DetailFlow.vue'
import AttendanceTripDetailFlow from './modules/attendance/trip/modules/DetailFlow.vue'
import AttendanceOverTimeForLeaveDetailFlow from './modules/attendance/overTimeForLeave/modules/DetailFlow.vue'
import AttendanceAbnormalOvertimeDetailFlow from './modules/attendance/abnormalOvertime/modules/DetailFlow.vue'
import AttendanceCardSignDetailFlow from './modules/attendance/cardSign/modules/DetailFlow.vue'
import AttendanceOutsideDetailFlow from './modules/attendance/outside/modules/DetailFlow.vue'
import AttendanceOutRequestDetailFlow from './modules/attendance/outRequest/modules/DetailFlow.vue'
import AttendanceDayOffDetailFlow from './modules/attendance/dayOff/modules/DetailFlow.vue'
import PersonnelResignationDetailFlow from './modules/personnel/resignation/modules/DetailFlow.vue'
import PersonnelEmployeesChanges from './modules/personnel/employeesChanges/modules/DetailFlow.vue'
import PersonnelRecruitmentNeeds from './modules/personnel/recruitmentNeeds/modules/DetailFlow.vue'
import PersonnelEmployeesDisciplinary from './modules/personnel/employeesDisciplinary/modules/DetailFlow.vue'
import PersonnelEmploymentApplication from './modules/personnel/employmentApplication/modules/DetailFlow.vue'
import CarUseApplyDetailFlow from './modules/carUse/apply/modules/DetailFlow.vue'

import { completeTask, refuseFlow } from '@/api/flowEngine/flowInterface'
import {
  pageList,
  saveTag,
  delUsetTagById,
  updateUsetTagById
} from '@/api/flowEngine/handleUserTag'

interface ITags {
  id?: string
  tagName: string
  tagType: '1'
  sort: number
}

const instanceId = ref('')
const taskId = ref('')
const userId = ref('')
const userName = ref('')
const optionType = ref('')
const id = ref('')
onLoad((option) => {
  console.log('option', option)
  instanceId.value = option.instanceId ? option.instanceId : ''
  taskId.value = option.taskId ? option.taskId : ''
  userId.value = option.userId ? option.userId : ''
  userName.value = option.userName ? option.userName : ''
  optionType.value = option.type ? option.type : ''
  id.value = option.id ? option.id : ''
})

const inputValue = ref('')
const inputVisible = ref(false)
const InputRef = ref(null)
let timer
const loading = reactive({
  submit: false,
  save: false,
  delete: false
})
const type = ref('')
const show = reactive({
  popup: false
})

// const widget = {
//   leave: AttendanceLeaveDetailFlow,
//   trip: AttendanceTripDetailFlow,
//   leaveClose: AttendanceLeaveDetailFlowClose,
//   tripClose: AttendanceTripDetailFlowClose,
//   overTimeForLeave: AttendanceOverTimeForLeaveDetailFlow,
//   abnormalOvertime: AttendanceAbnormalOvertimeDetailFlow,
//   cardSign: AttendanceCardSignDetailFlow,
//   outside: AttendanceOutsideDetailFlow,
//   dayOff: AttendanceDayOffDetailFlow,
//   resignation: PersonnelResignationDetailFlow,
//   employeesChanges: PersonnelEmployeesChanges,
//   employeesDisciplinary: PersonnelEmployeesDisciplinary,
//   recruitmentNeeds: PersonnelRecruitmentNeeds,
//   employmentApplication: PersonnelEmploymentApplication,
//   useCarApply: CarUseApplyDetailFlow
// }

const auditOpinion = ref('')
const dynamicTags = ref<Array<ITags>>([])

onUnmounted(() => {
  clearTimeout(timer)
})

function getPageList() {
  pageList().then(res => {
    dynamicTags.value = res.data
  })
}
getPageList()
const popupRef = ref(null)
function onClickRefusePass(val) {
  type.value = val
  // show.popup = true
  popupRef.value.open('bottom')
}

function onClosed() {
  popupRef.value.close()
  auditOpinion.value = ''
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value!.focus()
  })
}

const handleClose = (item: ITags) => {
  loading.delete = true
  delUsetTagById({ id: item.id! }).then(res => {
    dynamicTags.value.splice(dynamicTags.value.findIndex(tag => tag?.id === item.id), 1)
  }).finally(() => {
    loading.delete = false
  })
}

const handleInputConfirm = () => {
  if (!inputValue.value) {
    inputVisible.value = false
    return
  }
  loading.save = true
  inputVisible.value = false
  const value = inputValue.value
  inputValue.value = ''
  saveTag({
    tagName: value,
    tagType: '1',
    sort: dynamicTags.value.length
  }).then(res => {
    inputValue.value = ''
    getPageList()
  }).finally(() => {
    loading.save = false
  })
}

function updateSort(evt) {
  evt.preventDefault()
  dynamicTags.value.forEach((item, index) => {
    if (item.sort !== index) {
      updateUsetTagById({
        id: item.id!,
        tagName: item.tagName,
        tagType: item.tagType,
        sort: index
      }).then(res => {
        item.sort = index
      })
    }
  })
}

function onApprove() {
  if (type.value === 'pass') {
    loading.submit = true
    completeTask({
      instanceId: instanceId.value,
      taskId: taskId.value,
      auditOpinion: auditOpinion.value ?? '同意',
      doUserId: userId.value,
      doUserName: userName.value,
      customData: {
        pass: '1'
      },
      addUserList: []
    }).then(res => {
      uni.showToast({
        title: res.msg
      })
      timer = setTimeout(() => {
        popupRef.value.close()
        uni.navigateBack({
          delta: 1
        })
      }, 1000)
    }).finally(() => {
      loading.submit = false
    })
  } else if (type.value === 'refuse') {
    loading.submit = true
    refuseFlow({
      instanceId: instanceId.value,
      taskId: taskId.value,
      auditOpinion: auditOpinion.value ?? '拒绝',
      doUserId: userId.value,
      doUserName: userName.value,
      customData: {
        pass: '0'
      },
      addUserList: []
    }).then(res => {
      uni.showToast({
        title: res.msg
      })
      timer = setTimeout(() => {
        popupRef.value.close()
        uni.navigateBack({
          delta: 1
        })
      }, 1000)
    }).finally(() => {
      loading.submit = false
    })
  }
}
</script>

<template>
  <view class="container">
    <view class="container__body" style="padding: 0;">
      <view class="container__card flex" style="padding: 0;">
        <AttendanceLeaveDetailFlow v-if="optionType === 'leave'" :id="id" :instanceId="instanceId" />
        <AttendanceTripDetailFlow v-if="optionType === 'trip'" :id="id" :instanceId="instanceId" />
        <AttendanceLeaveDetailFlowClose v-if="optionType === 'leaveClose'" :id="id" :instanceId="instanceId" />
        <AttendanceTripDetailFlowClose v-if="optionType === 'tripClose'" :id="id" :instanceId="instanceId" />
        <AttendanceOverTimeForLeaveDetailFlow v-if="optionType === 'overTimeForLeave'" :id="id" :instanceId="instanceId" />
        <AttendanceAbnormalOvertimeDetailFlow v-if="optionType === 'abnormalOvertime'" :id="id" :instanceId="instanceId" />
        <AttendanceCardSignDetailFlow v-if="optionType === 'cardSign'" :id="id" :instanceId="instanceId" />
        <AttendanceOutsideDetailFlow v-if="optionType === 'outside'" :id="id" :instanceId="instanceId" />
         <AttendanceOutRequestDetailFlow v-if="optionType === 'outRequest'" :id="id" :instanceId="instanceId" />
        



        <AttendanceDayOffDetailFlow v-if="optionType === 'dayOff'" :id="id" :instanceId="instanceId" />
        <PersonnelResignationDetailFlow v-if="optionType === 'resignation'" :id="id" :instanceId="instanceId" />
        <PersonnelEmployeesChanges v-if="optionType === 'employeesChanges'" :id="id" :instanceId="instanceId" />
        <PersonnelEmployeesDisciplinary v-if="optionType === 'employeesDisciplinary'" :id="id" :instanceId="instanceId" />
        <PersonnelRecruitmentNeeds v-if="optionType === 'recruitmentNeeds'" :id="id" :instanceId="instanceId" />
        <PersonnelEmploymentApplication v-if="optionType === 'employmentApplication'" :id="id" :instanceId="instanceId" />
        <CarUseApplyDetailFlow v-if="optionType === 'useCarApply'" :id="id" :instanceId="instanceId" />
      </view>
    </view>
    <view class="float-bottom-button">
      <uv-button customStyle="width: 325rpx;" plain @click="onClickRefusePass('refuse')">拒绝</uv-button>
      <uv-button customStyle="width: 325rpx;" type="primary" @click="onClickRefusePass('pass')">同意</uv-button>
    </view>
    
    <uv-popup ref="popupRef" mode="bottom" closeable round="10" :close-on-click-overlay="false" @close="onClosed">
      <view class="popup-content">
        <view class="popup-title">确认{{ type === 'pass' ? '通过' : '拒绝' }}</view>
        <uv-textarea v-model="auditOpinion" placeholder="请输入审批意见" count maxlength="300" height="150"></uv-textarea>
        
        <view class="popup-tips-title">推荐回复</view>
        <view class="popup-tags">
          <uv-tags
            v-for="(item, index) in dynamicTags" 
            :key="index"
            type="primary"
            closeable
            @close="handleClose(item)"
            @click="auditOpinion += item.tagName"
            class="tag-item"
            :text="item.tagName"
          >

          </uv-tags>
          
          <uv-input 
            v-if="inputVisible"
            ref="InputRef"
            v-model="inputValue"
            @confirm="handleInputConfirm"
            @blur="handleInputConfirm"
            placeholder="请输入标签"
            class="tag-input"
          />
          <uv-button 
            v-else
            type="primary"
            plain
            icon="plus"
            size="small"
            :loading="loading.save"
            @click="showInput"
            class="add-tag-btn"
          >
            新增
          </uv-button>
        </view>
        
        <uv-button 
          type="primary" 
          :loading="loading.submit"
          @click="onApprove"
          class="submit-btn"
        >
          确认{{ type === 'pass' ? '通过' : '拒绝'}}
        </uv-button>
      </view>
    </uv-popup>
  </view>
</template>

<style lang="scss" scoped>
.container {
  position: relative;
  padding-bottom: 100px;
  
  &__body {
    padding: 15px;
  }
  
  &__card {
    background-color: #fff;
    border-radius: 8px;
    padding: 15px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  }
}

.float-bottom-button {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  padding: 15px;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  z-index: 100;
  justify-content: space-between;
  .uv-button {
    flex: 1;
    
    &:first-child {
      margin-right: 15px;
    }
  }
}

.popup-content {
  padding: 20px;
  padding-bottom: 40px;
}

.popup-title {
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
}

.popup-tips-title {
  margin: 20px 0 10px;
  color: #666;
  font-size: 14px;
}

.popup-tags {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20px;
  
  .tag-item {
    margin-right: 10px;
    margin-bottom: 10px;
  }
  
  .tag-input {
    width: 100px;
    height: 32px;
    margin-right: 10px;
    margin-bottom: 10px;
  }
  
  .add-tag-btn {
    height: 32px;
    margin-bottom: 10px;
  }
}

.submit-btn {
  width: 100%;
}
</style>