<template>
  <div class="daily-paper-count">
    <el-dialog v-model="isShowDialog" @close="onCancel" width="65vw" :close-on-click-modal="false" :destroy-on-close="true">
      <template #header>
        <div v-drag="['.daily-paper-count .el-dialog', '.daily-paper-count .el-dialog__header']" style="font-size: 18px">
          {{ infoDetail.name }} 日报填写
        </div>
      </template>
      <div class="box">
        <div class="box-left">
          <el-table
            v-loading="loading"
            :data="tableData"
            height="64vh"
            :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{ textAlign: 'center' }"
            border
            :row-key="tableKey"
            :expand-row-keys="expandRowKeys"
            @expand-change="clickOpen"
          >
            <el-table-column type="expand">
              <template #default="{ row: propsRow }">
                <div style="margin-left: 45px" m="4">
                  <el-table
                    :border="true"
                    :data="propsRow.detail"
                    :header-cell-style="{ 'text-align': 'center' }"
                    :cell-style="{ 'text-align': 'center' }"
                    highlight-current-row
                  >
                    <el-table-column label="序号" type="index" width="60px" />
                    <el-table-column label="计划日期" prop="date" />
                    <el-table-column label="数量" prop="planNum" width="60" />
                    <el-table-column label="完成量" prop="finishedNum" width="60" />
                    <el-table-column label="AI填报" prop="autoFill" width="60" />
                    <el-table-column label="操作" class-name="small-padding" width="200px" fixed="right">
                      <template #default="{ row: scopeRow, $index }">
                        <el-button type="primary" link @click="handleDayAdd(scopeRow, propsRow)">
                          <el-icon><ele-Plus /></el-icon>日报
                        </el-button>
                        <el-button type="success" link @click="handleView(scopeRow, propsRow)">
                          <el-icon><ele-View /></el-icon>查看
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="序号" type="index" :index="indexMethod" width="60px" />
            <el-table-column label="计划数量" prop="planNum" min-width="100px" />
            <el-table-column label="完成数量" prop="finishedNum" min-width="100px" />
            <el-table-column label="延期量" min-width="100px">
              <template #default="{ row: scopeRow }">
                <el-tag :type="filterW(scopeRow) ? 'danger' : 'success'">
                  {{ filterW(scopeRow) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="AI填报" prop="autoFill" min-width="100px" />
            <el-table-column label="开始时间" min-width="100px">
              <template #default="{ row: scopeRow }">
                <span>{{ scopeRow.startAt.split(' ')[0] }}</span>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getWorkList"
            layout="total, sizes, prev, pager, next"
            :isSmall="5"
          />
        </div>
        <div class="box_right" v-if="showDayWork">
          <div class="time_submit">
            <span>{{ formDetail.submitTime }}</span>
            <el-button type="primary" :disabled="!checkedList.length || flag" @click="onUploadDaily" size="large">
              <el-icon><ele-Upload /></el-icon>提交日报
            </el-button>
          </div>
          <el-table
            v-loading="loading1"
            height="58vh"
            :data="detialList"
            @selection-change="handleSelectionChange"
            :row-key="(row) => row.id"
            ref="multipleTableRef"
          >
            <el-table-column label="未完成工作" align="center">
              <el-table-column :reserve-selection="true" type="selection" width="55" align="center" />
              <el-table-column label="序号" align="center" type="index" width="60px" />
              <el-table-column label="编号" align="center" prop="name" min-width="100px" />
              <el-table-column label="状态" align="center" min-width="100px">
                <template #default="{ row: scopeRow }">
                  <el-tag :type="typeList[scopeRow.status]">
                    {{ filterStatus(scopeRow.status) }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table-column>
          </el-table>
          <pagination
            v-show="detailTotal > 0"
            :total="detailTotal"
            v-model:page="detailQueryParams.pageNum"
            v-model:limit="detailQueryParams.pageSize"
            @pagination="getPvModuleList"
            layout="total, sizes, prev, pager, next"
            :isSmall="5"
          />
        </div>
        <div class="box_right" v-else>
          <div class="time_submit">
            <span>{{ formDetail.submitTime }}</span>
            <el-button type="danger" :disabled="single" @click="handleRemove(null)" size="large">
              <el-icon><ele-SemiSelect /></el-icon>批量移除
            </el-button>
          </div>
          <el-table
            v-loading="loading2"
            height="58vh"
            :data="detialWordList"
            @selection-change="handleSelectionChangeWork"
            :row-key="(row) => row.id"
            ref="multipleTableWorkRef"
          >
            <el-table-column label="已完成工作" align="center">
              <el-table-column :reserve-selection="true" type="selection" width="55" align="center" />
              <el-table-column label="序号" align="center" type="index" width="60px" />
              <el-table-column label="编号" align="center" prop="name" min-width="100px" />
              <el-table-column label="填报方式" align="center" prop="status" min-width="100px">
                <template #default="{ row: scopeRow }">
                  <span v-if="scopeRow.status === 2">手动填报</span>
                  <span v-if="scopeRow.status === 3">AI识别</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" min-width="100px">
                <template #default="{ row: scopeRow }">
                  <el-button type="danger" link @click="handleRemove(scopeRow)">
                    <el-icon><ele-SemiSelect /></el-icon>移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table-column>
          </el-table>
          <pagination
            v-show="detailTotalWork > 0"
            :total="detailTotalWork"
            v-model:page="detailQueryParamsWork.pageNum"
            v-model:limit="detailQueryParamsWork.pageSize"
            @pagination="getPvModuleList"
            layout="total, sizes, prev, pager, next"
            :isSmall="5"
          />
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="onCancel" size="large">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { workScheduleList, pvModuleList, addDaily, getDailyBook, deleteDaily } from '@/api/progress/plan';
import { workScheduleListQuery } from '@/api/progress/plan/types';

// 响应式状态
const state = reactive<{
  expandRowKeys: number[];
  loading: boolean;
  isShowDialog: boolean;
  queryParams: workScheduleListQuery;
  infoDetail: { name: string };
  tableData: any[];
  total: number;
  formDetail: {
    workId: string;
    id: string;
    submitTime: string;
    finishedNum: number;
  };
  detialList: any[];
  detailTotal: number;
  detailQueryParams: {
    pageSize: number;
    pageNum: number;
  };
  loading1: boolean;
  loading2: boolean;
  typeList: ('info' | 'warning' | 'success' | 'danger')[];
  checkedList: number[];
  updateRow: any | null;
  showDayWork: boolean;
  detialWordList: any[];
  detailTotalWork: number;
  detailQueryParamsWork: {
    pageSize: number;
    pageNum: number;
  };
  single: boolean;
  checkList: number[];
  flag: boolean;
}>({
  expandRowKeys: [],
  loading: false,
  isShowDialog: false,
  queryParams: {
    pageSize: 10,
    pageNum: 1,
    progressCategoryId: ''
  },
  infoDetail: { name: '' },
  tableData: [],
  total: 0,
  formDetail: {
    workId: '',
    id: '',
    submitTime: '选择日期',
    finishedNum: 0
  },
  detialList: [],
  detailTotal: 0,
  detailQueryParams: {
    pageSize: 20,
    pageNum: 1
  },
  loading1: false,
  loading2: false,
  typeList: ['info', 'warning', 'success', 'danger'],
  checkedList: [],
  updateRow: null,
  showDayWork: true,
  detialWordList: [],
  detailTotalWork: 0,
  detailQueryParamsWork: {
    pageSize: 20,
    pageNum: 1
  },
  single: true,
  checkList: [],
  flag: false
});

// 引用refs
const multipleTableRef = ref();
const multipleTableWorkRef = ref();

// 状态解包
const {
  expandRowKeys,
  loading,
  isShowDialog,
  queryParams,
  infoDetail,
  tableData,
  total,
  formDetail,
  detialList,
  detailTotal,
  detailQueryParams,
  loading1,
  loading2,
  typeList,
  checkedList,
  updateRow,
  showDayWork,
  detialWordList,
  detailTotalWork,
  detailQueryParamsWork,
  single,
  checkList,
  flag
} = toRefs(state);

// 状态过滤函数
const filterStatus = (val: number): string => {
  switch (val) {
    case 0:
      return '未开始';
    case 1:
      return '进行中';
    case 2:
      return '已完成';
    case 3:
      return '已延期';
    default:
      return '';
  }
};

// 打开弹窗
const openDialog = (row: any) => {
  resetForm(false);
  formDetail.value.submitTime = '';
  queryParams.value.progressCategoryId = row.id;
  formDetail.value.workId = row.work_id;
  infoDetail.value = row;
  state.isShowDialog = true;
  getWorkList(true);
};

const resetForm = (bool: boolean) => {
  showDayWork.value = bool;
  detialList.value = [];
  detialWordList.value = [];
};

// 获取未完成数据
const getPvModuleList = () => {
  loading1.value = true;
  pvModuleList({
    workId: formDetail.value.workId,
    ...detailQueryParams.value,
    type: infoDetail.value.work_type,
    status: 0
  }).then((res: any) => {
    loading1.value = false;
    if (res.code === 0) {
      detialList.value = res.data.list;
      detailTotal.value = res.data.total;
    }
  });
};

// 获取计划列表
const getWorkList = (bool = false) => {
  loading.value = true;
  workScheduleList(queryParams.value).then((res: any) => {
    if (res.code === 0) {
      state.tableData = res.data.list.map((item: any, i: number) => {
        item.index = i + 1;
        item.autoFill = item.detail?.reduce((sum: number, child: any) => sum + child.autoFill, 0) || 0;
        return item;
      });
      state.total = res.data.total;
    }
    loading.value = false;
  });
};

// 关闭弹窗
const onCancel = () => {
  closeDialog();
};

const closeDialog = () => {
  isShowDialog.value = false;
  emit('getProgressList');
};

// 自定义序号
const indexMethod = (index: number): number => {
  const currentPage = queryParams.value.pageNum - 1;
  return currentPage > -1 ? index + 1 + currentPage * queryParams.value.pageSize : index + 1;
};

// 日报添加
const handleDayAdd = (row: any, obj: any) => {
  resetForm(true);
  formDetail.value.id = obj.id;
  formDetail.value.submitTime = row.date;
  state.updateRow = row;
  getPvModuleList();
};

const tableKey = (row: any) => row.id;

// 展开行处理
const clickOpen = (row: any) => {
  const index = state.expandRowKeys.indexOf(row.id);
  index === -1 ? state.expandRowKeys.push(row.id) : state.expandRowKeys.splice(index, 1);
  state.expandRowKeys = [...new Set(state.expandRowKeys)];
};

// 多选框处理
const handleSelectionChange = (selection: any[]) => {
  state.checkedList = selection.map((item: any) => item.id);
};

// 提交日报
const onUploadDaily = () => {
  if (!checkedList.value.length) {
    ElMessage.warning('请添加完成的任务编号');
    return;
  }

  const obj = {
    ids: checkedList.value,
    workID: formDetail.value.workId,
    doneTime: formDetail.value.submitTime,
    planID: formDetail.value.id
  };

  state.flag = true;
  addDaily(obj).then((res: any) => {
    if (res.code === 0) {
      ElMessage.success('添加成功');
      if (state.updateRow) {
        state.updateRow.finishedNum += checkedList.value.length;
      }
      checkedList.value = [];
      multipleTableRef.value?.clearSelection();
      getPvModuleList();
    } else {
      ElMessage.error(res.message);
    }
    state.flag = false;
  });
};

// 查看日报
const handleView = (row: any, obj: any) => {
  resetForm(false);
  getDailyBookList(row.date);
  state.updateRow = row;
  formDetail.value.id = obj.id;
  formDetail.value.submitTime = row.date;
  showDayWork.value = false;
};

// 获取已填日报
const getDailyBookList = (doneTime: string) => {
  detialWordList.value = [];
  getDailyBook({
    workId: formDetail.value.workId,
    type: infoDetail.value.work_type,
    doneTime
  }).then((res: any) => {
    if (res.code === 0) {
      detialWordList.value = res.data.list || [];
    } else {
      ElMessage.error(res.message);
    }
  });
};

// 选中处理（已完成）
const handleSelectionChangeWork = (selection: any[]) => {
  state.checkList = selection.map((item: any) => item.id);
  state.single = selection.length === 0;
};

// 移除日报
const handleRemove = (row?: any) => {
  const planID = row ? [row.id] : state.checkList;
  const obj = {
    planID,
    id: formDetail.value.id,
    workID: formDetail.value.workId,
    time: formDetail.value.submitTime
  };

  ElMessageBox.confirm('确认移除该条数据?', '温馨提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      deleteDaily(obj).then((res: any) => {
        if (res.code === 0) {
          ElMessage.success('移除成功');
          if (state.updateRow) {
            state.updateRow.finishedNum -= planID.length;
          }
          getDailyBookList(formDetail.value.submitTime);
        } else {
          ElMessage.error(res.message);
        }
      });
    })
    .catch(() => {});
};

// 延期计算
const filterW = (row: any): number => {
  const { finishedNum, planNum, endAt } = row;
  if (!endAt) return 0;

  const endTime = new Date(endAt).getTime();
  const now = new Date().getTime();

  if (endTime <= now && planNum > finishedNum) {
    return planNum - finishedNum;
  }
  return 0;
};

// 暴露给模板的属性和方法
defineExpose({
  openDialog,
  closeDialog
});
const emit = defineEmits(['getProgressList']);
</script>

<style lang="scss" scoped>
.daily-paper-count {
  width: 100%;

  .box {
    display: flex;
    width: 100%;
    justify-content: space-between;
    padding: 0 10px;

    .box-left {
      width: 50%;
      float: left;
    }

    .box_right {
      width: 46%;
      float: left;
      border: 1px solid #ebeef5;
      height: 64vh;
      margin-left: 20px;

      .time_submit {
        width: 100%;
        padding: 10px;
        box-sizing: border-box;
        display: flex;
        justify-content: space-between;

        > span {
          font-size: 20px;
          font-family: revert;
        }
      }
    }
  }

  .pagination-container {
    padding: 10px 10px !important;
  }

  .el-drawer__title {
    font-size: 18px;
  }
}
</style>
