<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
            <el-form-item label="申请人" prop="userName">
              <el-input v-model="queryParams.userName" placeholder="请输入申请人" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="所属班组" prop="leaveType">
              <el-select v-model="queryParams.teamId" placeholder="全部" clearable>
                <el-option v-for="dict in ProjectTeam" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="请假类型" prop="leaveType">
              <el-select v-model="queryParams.leaveType" placeholder="请选择请假类型" clearable>
                <el-option v-for="dict in user_leave_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item> -->
            <el-form-item label="班组长意见" prop="gangerOpinion">
              <el-select v-model="queryParams.gangerOpinion" placeholder="全部" clearable>
                <el-option v-for="dict in user_opinion_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="管理员意见" prop="managerOpinion">
              <el-select v-model="queryParams.managerOpinion" placeholder="全部" clearable>
                <el-option v-for="dict in user_opinion_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <!-- <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['project:leave:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['project:leave:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['project:leave:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['project:leave:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template> -->

      <el-table v-loading="loading" :data="leaveList">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" type="index" width="50" />
        <el-table-column label="申请人" align="center" prop="userName" />
        <el-table-column label="申请请假说明" align="center" prop="argument" />
        <!-- <el-table-column label="请假申请时间" align="center" prop="userTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.userTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="所属班组" align="center" prop="teamName">
          <template #default="scope">
            <dict-tag :options="user_leave_type" :value="scope.row.teamName" />
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="cardNumber">
          <template #default="scope">
            <dict-tag :options="user_review_status_type" :value="scope.row.cardNumber" />
          </template>
        </el-table-column>
        <!-- <el-table-column label="班组长意见" align="center" prop="gangerOpinion">
          <template #default="scope">
            <dict-tag :options="user_opinion_type" :value="scope.row.gangerOpinion" />
          </template>
        </el-table-column>
        <el-table-column label="班组长说明" align="center" prop="gangerExplain" />
        <el-table-column label="班组长操作时间" align="center" prop="gangerTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.gangerTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="管理员意见" align="center" prop="managerOpinion">
          <template #default="scope">
            <dict-tag :options="user_opinion_type" :value="scope.row.managerOpinion" />
          </template>
        </el-table-column>
        <el-table-column label="管理员说明" align="center" prop="managerExplain" />
        <el-table-column label="请假申请时间" align="center" prop="userTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.userTime) }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="success" icon="View" @click="handleDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 审批对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <div class="pl-xl">
        <el-form-item label="是否同意">
          <el-radio-group v-model="auditForm.managerOpinion">
            <el-radio value="2" size="small">同意</el-radio>
            <el-radio value="3" size="small">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="拒绝说明" v-if="auditForm.managerOpinion == '3'">
          <el-input v-model="auditForm.managerExplain" placeholder="请输入拒绝说明" type="textarea" clearable></el-input>
        </el-form-item>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 详情对话框 -->
    <el-dialog :title="detailObj.userName + '补卡申请详情'" v-model="dialog.details" width="700px" append-to-body>
      <div class="block_box">
        <span>补卡申请</span>
        <el-form label-width="130px">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="补卡申请时间">
                {{ detailObj.userTime }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="班组长说明">
                {{ detailObj.gangerExplain ? detailObj.gangerExplain : '暂无' }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="班组长操作时间">
                {{ detailObj.gangerTime ? detailObj.gangerTime : '暂无' }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="管理员说明">
                {{ detailObj.managerExplain ? detailObj.managerExplain : '暂无' }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="管理员操作时间">
                {{ detailObj.managerTime ? detailObj.managerTime : '暂无' }}
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="block_box">
        <span>审核进度</span>
        <el-steps style="max-width: 700px" :active="auditProgress" align-center finish-status="success">
          <el-step :title="teamStatus ? detailObj.gangerName : '班组长'" :status="teamStatus ? teamStatus : ''">
            <template #description>
              <div v-if="!teamStatus">审核中</div>
              <div v-else>
                <span>{{ detailObj.gangerOpinion == '2' ? '同意' : '拒绝' }}</span>
              </div>
            </template>
          </el-step>
          <el-step
            :title="managerStatus ? detailObj.managerName : '管理员'"
            :status="managerStatus ? managerStatus : ''"
            v-if="detailObj.gangerOpinion != '3'"
          >
            <template #description>
              <div v-if="!managerStatus">审核中</div>
              <div v-else>
                <span>{{ detailObj.managerOpinion == '2' ? '同意' : '拒绝' }}</span>
              </div>
            </template>
          </el-step>
          <el-step title="结果" :status="resultsStatus">
            <template #description>
              <div>{{ user_review_status_type[parseInt(detailObj.cardNumber) - 1].label }}</div>
            </template>
          </el-step>
        </el-steps>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Leave" lang="ts">
import { listLeave, getLeave, delLeave, addLeave, updateLeave, AuditReissueCard } from '@/api/project/leave';
import { LeaveVO, LeaveQuery, LeaveForm } from '@/api/project/leave/types';
import { listProjectTeam } from '@/api/project/projectTeam';
import { ProjectTeamVO } from '@/api/project/projectTeam/types';
import { AuditReissueCardForm, ReissueCardVO } from '@/api/project/reissueCard/types';
import { useUserStoreHook } from '@/store/modules/user';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { user_leave_type, user_opinion_type, user_review_status_type } = toRefs<any>(
  proxy?.useDict('user_leave_type', 'user_opinion_type', 'user_review_status_type')
);
const detailObj = ref<ReissueCardVO>({
  userName: undefined,
  id: undefined,
  userExplain: undefined,
  userTime: undefined,
  gangerName: undefined,
  gangerOpinion: undefined,
  gangerExplain: undefined,
  gangerTime: undefined,
  managerOpinion: undefined,
  managerExplain: undefined,
  managerTime: undefined,
  remark: undefined,
  status: undefined,
  managerName: undefined
});

const leaveList = ref<LeaveVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const leaveFormRef = ref<ElFormInstance>();
const dialog = reactive<DialogOption>({
  visible: false,
  title: '',
  details: false
});
// 获取用户 store
const userStore = useUserStoreHook();
// 从 store 中获取项目列表和当前选中的项目
const currentProject = computed(() => userStore.selectedProject);
const ProjectTeam = computed(() => proxy?.$cache.local.getJSON('ProjectTeamList') || []);

const initFormData: LeaveForm = {
  id: undefined,
  userId: undefined,
  userName: undefined,
  userExplain: undefined,
  userTime: undefined,
  leaveType: undefined,
  startTime: undefined,
  endTime: undefined,
  gangerId: undefined,
  gangerName: undefined,
  gangerOpinion: undefined,
  gangerExplain: undefined,
  gangerTime: undefined,
  managerOpinion: undefined,
  managerExplain: undefined,
  managerTime: undefined,
  projectId: undefined,
  teamId: undefined,
  remark: undefined
};
const data = reactive<PageData<LeaveForm, LeaveQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: undefined,
    leaveType: undefined,
    gangerOpinion: undefined,
    managerOpinion: undefined,
    projectId: undefined,
    teamId: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键id不能为空', trigger: 'blur' }],
    userId: [{ required: true, message: '申请人id不能为空', trigger: 'blur' }],
    userName: [{ required: true, message: '申请人名字不能为空', trigger: 'blur' }],
    leaveType: [{ required: true, message: '请假类型不能为空', trigger: 'change' }],
    startTime: [{ required: true, message: '请假开始时间不能为空', trigger: 'blur' }],
    endTime: [{ required: true, message: '请假结束时间不能为空', trigger: 'blur' }],
    gangerOpinion: [{ required: true, message: '班组长意见不能为空', trigger: 'change' }],
    managerOpinion: [{ required: true, message: '管理员意见不能为空', trigger: 'change' }],
    projectId: [{ required: true, message: '项目id不能为空', trigger: 'blur' }]
  }
});
const auditForm = reactive<AuditReissueCardForm>({
  id: undefined,
  managerOpinion: '2',
  managerExplain: undefined
});
const { queryParams, form, rules } = toRefs(data);

//审核进度
const auditProgress = computed(() => {
  if (auditStatus.value) return 3;
  if (managerStatus.value) return 2;
  if (teamStatus.value) return 1;
  return 0;
});
//审核状态
const auditStatus = computed(() => {
  if (detailObj.value.status == '3' || detailObj.value.status == '4') return true;
  return false;
});
//管理员审核状态
const managerStatus = computed(() => {
  switch (detailObj.value.managerOpinion) {
    case '1':
      return false;
    case '2':
      return 'success';
    case '3':
      return 'error';
  }
});
//班组审核状态
const teamStatus = computed(() => {
  switch (detailObj.value.gangerOpinion) {
    case '1':
      return false;
    case '2':
      return 'success';
    case '3':
      return 'error';
  }
});
//结果状态
const resultsStatus = computed(() => {
  if (detailObj.value.status == '3') return 'success';
  if (detailObj.value.status == '4') return 'error';
  return '';
});

/** 查询施工人员请假申请列表 */
const getList = async () => {
  loading.value = true;
  const res = await listLeave(queryParams.value);
  leaveList.value = res.data.list;
  total.value = res.data.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 提交按钮 */
const submitForm = async () => {
  await AuditReissueCard(auditForm);
  proxy?.$modal.msgSuccess('审批成功');
  dialog.visible = false;

  await getList();
};

const handleDetail = (row: ReissueCardVO) => {
  detailObj.value = row;
  console.log('🚀 ~ handleDetail ~ row:', row);

  dialog.details = true;
};

/** 审批按钮操作 */
const handleUpdate = async (row?: LeaveVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  auditForm.id = _id;
  dialog.visible = true;
  dialog.title = '修改施工人员补卡申请';
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'project/leave/export',
    {
      ...queryParams.value
    },
    `leave_${new Date().getTime()}.xlsx`
  );
};

//监听项目id刷新数据
const listeningProject = watch(
  () => currentProject.value.id,
  (nid, oid) => {
    queryParams.value.projectId = nid;
    form.value.projectId = nid;
    getList();
  }
);

onUnmounted(() => {
  listeningProject();
});

onMounted(() => {
  getList();
});
</script>
<style lang="scss" scoped>
.block_box {
  border: 1px solid #9eccfa;
  border-radius: 6px;
  padding: 10px 20px 20px 10px;
  margin: 15px;
  > span {
    color: #409eff;
    font-weight: 700;
    font-size: 14px;
  }
}
</style>
