<script setup lang="ts">
import type { ApprovalType } from '../type';

import type { TaskInfo } from '#/api/workflow/task/model';

import { computed, reactive, ref } from 'vue';

import { cn } from '@vben/utils';

import { UploadFilled } from '@element-plus/icons-vue';
import {
  ElButton,
  ElDrawer,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElMessageBox,
  ElOption,
  ElSelect,
  ElSpace,
  ElTreeSelect,
  ElUpload,
} from 'element-plus';

import { requestClient } from '#/api/request';
import { backProcess, deleteOrder, submitOrder } from '#/api/workflow/task';
import { getSingleImageUploadConfig } from '#/components/upload/config';
import CreatOrder from '#/views/workflow/order/creatOrder.vue';

interface Props {
  /**
   * 行数据的taskInfo?
   */
  task?: TaskInfo;
  /**
   * 工单详情
   */
  workOrderDetail?: any;
  /**
   * 审批类型 根据不同类型显示按钮
   */
  type: ApprovalType;
  /**
   * 为审批类型时候 显示的按钮(按钮权限)
   */
  buttonPermissions?: Record<string, boolean>;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  reload: [];
}>();

// 创建CreatOrder组件的ref
const creatOrderRef = ref<InstanceType<typeof CreatOrder>>();

/**
 * 是否可编辑/删除
 */
const editableAndRemoveable = computed(() => {
  if (!props.task) {
    return false;
  }
  return ['back', 'cancel', 'draft'].includes(props.task.flowStatus);
});

// 使用普通的el-drawer
const drawerVisible = ref(false);
const drawerId = ref<string>('');

// 处理工单的抽屉
const handleDrawerVisible = ref(false);
const handleFormData = reactive({
  attachments: '',
  processContent: '',
  taskId: '',
});
const handleFileList = ref([]);

// 延时申请的抽屉
const delayDrawerVisible = ref(false);
const delayFormData = reactive({
  applyFile: '',
  delayDuration: 0,
  delayReason: '',
  taskId: 0,
});
const delayFileList = ref([]);

// 抄送的抽屉
const ccDrawerVisible = ref(false);
const ccFormData = reactive({
  ccUserIds: '',
  taskId: 0,
});
const deptTree = ref([]);
const userList = ref([]);
const selectedDeptId = ref('');
const selectedUsers = ref([]);

// 延时审批的抽屉
const approveDelayDrawerVisible = ref(false);
const approveDelayFormData = reactive({
  approveRemark: '',
  approveStatus: '1',
  delayId: 0,
  newDeadline: '',
});

// 编辑
const handleEdit = () => {
  drawerId.value = props.workOrderDetail!.id;
  drawerVisible.value = true;
};

// 关闭抽屉
const handleCloseDrawer = () => {
  drawerVisible.value = false;
  emit('reload');
};

// 确认编辑
const handleConfirmEdit = async () => {
  if (creatOrderRef.value) {
    await creatOrderRef.value.handleSubmit();
  }
};

// 抽屉关闭后的回调
const handleDrawerClosed = () => {
  drawerId.value = '';
};

// 上传成功回调
const handleUploadSuccess = (response, file, fileList) => {
  if (response.code === 200) {
    // 将文件路径添加到attachments字段
    const paths = fileList.map((f) => f.response.data.fileName).join(',');
    handleFormData.attachments = paths;
  } else {
    ElMessage.error('文件上传失败');
  }
};

// 上传失败回调
const handleUploadError = (error) => {
  ElMessage.error('文件上传失败');
  console.error('文件上传失败:', error);
};

// 移除文件回调
const handleFileRemove = (file, fileList) => {
  // 更新attachments字段（文件名）
  const fileNames = fileList.map((f) => f.response.data.fileName).join(',');
  handleFormData.attachments = fileNames;
};

// 延时申请上传成功回调
const handleDelayUploadSuccess = (response, file, fileList) => {
  if (response.code === 200) {
    // 将文件路径添加到applyFile字段
    const paths = fileList.map((f) => f.response.data.fileName).join(',');
    delayFormData.applyFile = paths;
  } else {
    ElMessage.error('附件上传失败');
  }
};

// 延时申请移除文件回调
const handleDelayFileRemove = (file, fileList) => {
  // 更新applyFile字段（文件名）
  const fileNames = fileList.map((f) => f.response.data.fileName).join(',');
  delayFormData.applyFile = fileNames;
};

// 处理工单提交
async function handleSubmitForm() {
  try {
    // 验证处理内容
    if (!handleFormData.processContent.trim()) {
      ElMessage.error('请输入处理内容');
      return;
    }

    // 调用处理接口
    await requestClient.put('/workOrder/order/handle', handleFormData);
    ElMessage.success('工单处理成功');

    // 关闭抽屉
    handleDrawerVisible.value = false;

    // 重新加载数据
    emit('reload');
  } catch (error) {
    ElMessage.error('工单处理失败');
    console.error('工单处理失败:', error);
  }
}

// 删除
function handleRemove() {
  ElMessageBox.confirm('确定删除该工单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    center: true,
  })
    .then(async () => {
      await deleteOrder([props.workOrderDetail!.id]);
      emit('reload');
    })
    .catch(() => {
      // 用户取消操作，不做任何处理
      console.log('用户取消了删除操作');
    });
}

// 提交
async function handleSubmit() {
  try {
    await ElMessageBox.confirm('确定要提交该工单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      center: true,
    });
    await submitOrder(props.workOrderDetail!.id);
    emit('reload');
  } catch {
    // 用户取消操作，不做任何处理
    console.log('用户取消了提交操作');
  }
}

// 处理
function handleApprove() {
  // 重置表单数据
  handleFormData.attachments = '';
  handleFormData.processContent = '';
  handleFormData.taskId = props.task!.taskId;
  handleFileList.value = [];

  // 打开抽屉
  handleDrawerVisible.value = true;
}

// 延时
function handleDelay() {
  // 重置表单数据
  delayFormData.taskId = props.task!.taskId;
  delayFormData.applyFile = '';
  delayFormData.delayDuration = 0;
  delayFormData.delayReason = '';
  delayFileList.value = [];

  // 打开抽屉
  delayDrawerVisible.value = true;
}

// 抄送
function handleCopy() {
  // 重置表单数据
  ccFormData.taskId = props.task!.taskId;
  ccFormData.ccUserIds = '';
  selectedDeptId.value = '';
  selectedUsers.value = [];
  userList.value = [];

  // 加载部门树
  loadDeptTree();

  // 打开抽屉
  ccDrawerVisible.value = true;
}

// 加载部门树
async function loadDeptTree() {
  try {
    const response = await requestClient.get('/system/user/deptTree');
    deptTree.value = response;
  } catch (error) {
    ElMessage.error('加载部门树失败');
    console.error('加载部门树失败:', error);
  }
}

// 加载人员列表
async function loadUserList(deptId) {
  try {
    const response = await requestClient.get(
      `/system/user/list?deptId=${deptId}&pageNum=1&pageSize=999`,
    );
    console.log('加载人员列表响应:', response);
    if (response.rows && response.rows.length > 0) {
      userList.value = response.rows || [];
    } else {
      ElMessage.error('加载人员列表失败');
    }
  } catch (error) {
    ElMessage.error('加载人员列表失败');
    console.error('加载人员列表失败:', error);
  }
}

// 部门选择变化回调
async function handleDeptChange(deptId) {
  if (deptId) {
    // 加载该部门下的人员
    await loadUserList(deptId);
  } else {
    // 清空人员列表和选择
    userList.value = [];
    selectedUsers.value = [];
    ccFormData.ccUserIds = '';
  }
}

// 人员选择变化回调
function handleUserChange(users) {
  // 更新ccUserIds字段（用逗号分隔）
  ccFormData.ccUserIds = users.join(',');
}

// 延时申请提交
async function handleDelaySubmit() {
  try {
    // 验证表单
    if (!delayFormData.delayReason.trim()) {
      ElMessage.error('请输入延时原因');
      return;
    }
    if (!delayFormData.delayDuration || delayFormData.delayDuration < 1) {
      ElMessage.error('请输入有效的延时时长(至少1小时)');
      return;
    }

    // 调用延时API
    await requestClient.put('/workOrder/order/delay', delayFormData);
    ElMessage.success('延时申请提交成功');

    // 关闭抽屉
    delayDrawerVisible.value = false;

    // 重新加载数据
    emit('reload');
  } catch (error) {
    ElMessage.error('延时申请提交失败');
    console.error('延时申请失败:', error);
  }
}

// 抄送提交
async function handleCCSubmit() {
  try {
    // 验证表单
    if (!selectedDeptId.value) {
      ElMessage.error('请选择部门');
      return;
    }
    if (!selectedUsers.value || selectedUsers.value.length === 0) {
      ElMessage.error('请选择人员');
      return;
    }

    // 调用抄送API
    await requestClient.put('/workOrder/order/cc', ccFormData);
    ElMessage.success('抄送成功');

    // 关闭抽屉
    ccDrawerVisible.value = false;

    // 重新加载数据
    emit('reload');
  } catch (error) {
    ElMessage.error('抄送失败');
    console.error('抄送失败:', error);
  }
}

// 退回
async function handleBack() {
  try {
    await ElMessageBox.confirm('确定要退回该工单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      center: true,
    });
    await backProcess({
      taskId: props.task!.taskId,
    });
    emit('reload');
  } catch {
    // 用户取消操作，不做任何处理
    console.log('用户取消了退回操作');
  }
}

// 延时审批
function handleApproveDelay() {
  // 重置表单数据
  console.log('props', props);
  approveDelayFormData.approveRemark = '';
  approveDelayFormData.approveStatus = '1';
  approveDelayFormData.delayId = Number(props.task!.id);
  approveDelayFormData.newDeadline = '';
  // 打开抽屉
  approveDelayDrawerVisible.value = true;
}

// 延时审批提交
async function handleApproveDelaySubmit() {
  try {
    // 验证表单
    if (!approveDelayFormData.approveRemark.trim()) {
      ElMessage.error('请输入审批意见');
      return;
    }
    if (!approveDelayFormData.newDeadline) {
      ElMessage.error('请选择新截止时间');
      return;
    }
    console.log('延时审批表单数据:', approveDelayFormData);
    // 调用延时审批API
    await requestClient.put(
      '/workOrder/order/approveDelay',
      approveDelayFormData,
    );
    ElMessage.success('延时审批操作成功');

    // 关闭抽屉
    approveDelayDrawerVisible.value = false;

    // 重新加载数据
    emit('reload');
  } catch (error) {
    ElMessage.error('延时审批操作失败');
    console.error('延时审批失败:', error);
  }
}
</script>

<template>
  <div
    :class="
      cn(
        'absolute bottom-0 left-0',
        'border-t-solid border-t-[1px]',
        'bg-background w-full p-3',
      )
    "
  >
    <div class="flex justify-end">
      <ElSpace v-if="type === 'myself'">
        <ElButton
          type="primary"
          v-if="buttonPermissions?.edit || editableAndRemoveable"
          @click="handleEdit"
        >
          编辑
        </ElButton>
        <ElButton
          v-if="buttonPermissions?.delete || editableAndRemoveable"
          type="danger"
          @click="handleRemove"
        >
          删除
        </ElButton>
        <!-- 提交按钮 -->
        <ElButton
          v-if="buttonPermissions?.submit"
          type="primary"
          @click="handleSubmit"
        >
          提交
        </ElButton>
      </ElSpace>

      <!-- 审批操作按钮 -->
      <ElSpace v-if="type === 'waiting'">
        <ElButton
          v-if="buttonPermissions?.handle"
          type="primary"
          @click="handleApprove"
        >
          处理
        </ElButton>
        <ElButton
          v-if="buttonPermissions?.delay"
          type="warning"
          @click="handleDelay"
        >
          延时
        </ElButton>
        <ElButton v-if="buttonPermissions?.cc" type="info" @click="handleCopy">
          抄送
        </ElButton>
        <ElButton v-if="buttonPermissions?.back" danger @click="handleBack">
          退回
        </ElButton>
      </ElSpace>
      <ElSpace v-if="type === 'delay'">
        <ElButton
          v-if="buttonPermissions?.approveDelay"
          type="primary"
          @click="handleApproveDelay"
        >
          延时审批
        </ElButton>
      </ElSpace>
    </div>
  </div>

  <!-- 普通的el-drawer组件 -->
  <ElDrawer
    v-model="drawerVisible"
    title="编辑工单"
    width="800px"
    :close-on-click-modal="false"
    @close="handleDrawerClosed"
    @closed="handleDrawerClosed"
  >
    <div class="drawer-content pb-20">
      <CreatOrder
        :id="drawerId"
        ref="creatOrderRef"
        @close="handleCloseDrawer"
      />
    </div>
    <div
      class="absolute bottom-0 left-0 right-0 border-t border-gray-200 bg-white p-4"
    >
      <div class="flex justify-end space-x-2">
        <ElButton @click="drawerVisible = false">取消</ElButton>
        <ElButton type="primary" @click="handleConfirmEdit">保存</ElButton>
      </div>
    </div>
  </ElDrawer>

  <!-- 处理工单的抽屉组件 -->
  <ElDrawer
    v-model="handleDrawerVisible"
    title="处理工单"
    width="800px"
    :close-on-click-modal="false"
  >
    <div class="drawer-content p-4 pb-20">
      <ElForm
        :model="handleFormData"
        label-width="120px"
        class="handle-order-form"
      >
        <!-- 处理内容 -->
        <ElFormItem label="处理内容" required>
          <ElInput
            v-model="handleFormData.processContent"
            type="textarea"
            :rows="4"
            placeholder="请输入处理内容"
          />
        </ElFormItem>

        <!-- 处理附件 -->
        <ElFormItem label="处理附件">
          <ElUpload
            :file-list="handleFileList"
            :action="getSingleImageUploadConfig().action"
            :headers="getSingleImageUploadConfig().headers"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :on-remove="handleFileRemove"
            list-type="picture-card"
            multiple
            :limit="5"
          >
            <UploadFilled />
            <template #tip>
              <div class="el-upload__tip">
                支持上传图片格式文件，最多5个，多个文件用逗号分隔
              </div>
            </template>
          </ElUpload>
        </ElFormItem>
      </ElForm>
    </div>
    <div
      class="absolute bottom-0 left-0 right-0 border-t border-gray-200 bg-white p-4"
    >
      <div class="flex justify-end space-x-2">
        <ElButton @click="handleDrawerVisible = false">取消</ElButton>
        <ElButton type="primary" @click="handleSubmitForm">提交</ElButton>
      </div>
    </div>
  </ElDrawer>

  <!-- 延时申请的抽屉组件 -->
  <ElDrawer
    v-model="delayDrawerVisible"
    title="延时申请"
    width="800px"
    :close-on-click-modal="false"
  >
    <div class="drawer-content p-4 pb-20">
      <ElForm
        :model="delayFormData"
        label-width="120px"
        class="delay-order-form"
      >
        <!-- 延时原因 -->
        <ElFormItem label="延时原因" required>
          <ElInput
            v-model="delayFormData.delayReason"
            type="textarea"
            :rows="4"
            placeholder="请输入延时原因"
          />
        </ElFormItem>

        <!-- 延时时长 -->
        <ElFormItem label="延时时长(小时)" required>
          <ElInput
            v-model.number="delayFormData.delayDuration"
            type="number"
            placeholder="请输入延时时长"
            min="1"
          />
        </ElFormItem>

        <!-- 申请附件 -->
        <ElFormItem label="申请附件">
          <ElUpload
            :file-list="delayFileList"
            :action="getSingleImageUploadConfig().action"
            :headers="getSingleImageUploadConfig().headers"
            :on-success="handleDelayUploadSuccess"
            :on-error="handleUploadError"
            :on-remove="handleDelayFileRemove"
            list-type="picture-card"
            multiple
            :limit="5"
          >
            <UploadFilled />
            <template #tip>
              <div class="el-upload__tip">
                支持上传图片格式文件，最多5个，多个文件用逗号分隔
              </div>
            </template>
          </ElUpload>
        </ElFormItem>
      </ElForm>
    </div>
    <div
      class="absolute bottom-0 left-0 right-0 border-t border-gray-200 bg-white p-4"
    >
      <div class="flex justify-end space-x-2">
        <ElButton @click="delayDrawerVisible = false">取消</ElButton>
        <ElButton type="primary" @click="handleDelaySubmit">提交</ElButton>
      </div>
    </div>
  </ElDrawer>

  <!-- 抄送的抽屉组件 -->
  <ElDrawer
    v-model="ccDrawerVisible"
    title="抄送"
    width="800px"
    :close-on-click-modal="false"
  >
    <div class="drawer-content p-4 pb-20">
      <ElForm :model="ccFormData" label-width="120px" class="cc-order-form">
        <!-- 部门选择 -->
        <ElFormItem label="选择部门" required>
          <ElTreeSelect
            v-model="selectedDeptId"
            check-strictly
            :data="deptTree"
            node-key="id"
            :props="{ label: 'label', children: 'children' }"
            placeholder="请选择部门"
            @change="handleDeptChange"
          />
        </ElFormItem>

        <!-- 人员选择 -->
        <ElFormItem label="选择人员" required>
          <ElSelect
            v-model="selectedUsers"
            multiple
            placeholder="请选择人员"
            @change="handleUserChange"
          >
            <ElOption
              v-for="user in userList"
              :key="user.userId"
              :label="
                user.nickName + (user.userName ? `(${user.userName})` : '')
              "
              :value="user.userId"
            />
          </ElSelect>
        </ElFormItem>
      </ElForm>
    </div>
    <div
      class="absolute bottom-0 left-0 right-0 border-t border-gray-200 bg-white p-4"
    >
      <div class="flex justify-end space-x-2">
        <ElButton @click="ccDrawerVisible = false">取消</ElButton>
        <ElButton type="primary" @click="handleCCSubmit">提交</ElButton>
      </div>
    </div>
  </ElDrawer>

  <!-- 延时审批的抽屉组件 -->
  <ElDrawer
    v-model="approveDelayDrawerVisible"
    title="延时审批"
    width="800px"
    :close-on-click-modal="false"
  >
    <div class="drawer-content p-4 pb-20">
      <ElForm
        :model="approveDelayFormData"
        label-width="120px"
        class="approve-delay-form"
      >
        <!-- 审批意见 -->
        <ElFormItem label="审批意见" required>
          <ElInput
            v-model="approveDelayFormData.approveRemark"
            type="textarea"
            :rows="4"
            placeholder="请输入审批意见"
          />
        </ElFormItem>

        <!-- 审核状态 -->
        <ElFormItem label="审核状态" required>
          <ElSelect
            v-model="approveDelayFormData.approveStatus"
            placeholder="请选择审核状态"
          >
            <ElOption label="审核通过" value="1" />
            <ElOption label="审核拒绝" value="2" />
          </ElSelect>
        </ElFormItem>

        <!-- 新截止时间 -->
        <ElFormItem label="新截止时间" required>
          <ElDatePicker
            v-model="approveDelayFormData.newDeadline"
            type="datetime"
            placeholder="请选择新截止时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </ElFormItem>
      </ElForm>
    </div>
    <div
      class="absolute bottom-0 left-0 right-0 border-t border-gray-200 bg-white p-4"
    >
      <div class="flex justify-end space-x-2">
        <ElButton @click="approveDelayDrawerVisible = false">取消</ElButton>
        <ElButton type="primary" @click="handleApproveDelaySubmit">
          提交
        </ElButton>
      </div>
    </div>
  </ElDrawer>
</template>
