<template>
  <div class="h5-container">
    <van-nav-bar title="检查任务" @click-left="onClickLeft"
                 @click-right="handAdd">
    </van-nav-bar>

    <!-- 项目列表 -->
    <van-pull-refresh v-model="isRefreshing" success-text="刷新成功" @refresh="onRefresh">
      <van-list
        v-model:loading="isLoading"
        :finished="isFinished"
        finished-text="没有更多了"
        @load="onLoad"
      >
          <div v-for="item in resultData" :key="item.id" class="card">
            <van-cell
              :label="`检查类型: ${item.checkType}, 受检单位: ${item.checkedDept}
              , 检查事由: ${item.checkThing}, 检查人: ${item.checkPersonName}, 检查时间: ${item.checkTime}, 状态: ${item.state}
              , 备注: ${item.notes}`"
              @click="edits(item)"
            >
              <template #title>
                <span class="cell-title">{{ item.checkThing }}</span>
              </template>
              <template #label>
                <div class="label-content">
                  <div>受检单位：{{ item.checkedDept }}</div>
                  <div>检查时间：{{ item.checkTime }}</div>
                </div>
              </template>
              <template #right-icon>
                <van-button
                  type="warning"
                  size="mini"
                  @click.stop="handleBatchXF(item)"
                >
                  一键下发
                </van-button>
              </template>
            </van-cell>
          </div>
      </van-list>
    </van-pull-refresh>


    <!-- 删除确认弹窗 -->
    <van-dialog
      v-model:show="deleteDialogVisible"
      title="删除确认"
      show-cancel-button
      @confirm="confirmDelete"
    >
      <div>确定要删除该项目吗？</div>
    </van-dialog>

    <!-- 一键下发弹窗 -->
    <van-dialog
      v-model:show="dialogBatchXFVisible"
      title="一键下发隐患"
      :show-confirm-button="false"
      :close-on-click-overlay="false"
    >
      <div class="batch-xf-body">
        <van-field
          readonly
          label="待下发"
          :model-value="`${batchPendingItems.length} 条不符合项`"
        />
        <van-field
          readonly
          is-link
          required
          label="隐患确认人"
          :model-value="xfConfirmDisplay"
          placeholder="请选择隐患确认人"
          @click="openXfConfirmPicker"
        />
        <div class="batch-xf-actions">
          <van-button
            block
            type="primary"
            :loading="batchSubmitting"
            @click="confirmBatchXF"
          >
            确定
          </van-button>
          <van-button
            block
            plain
            :disabled="batchSubmitting"
            @click="cancelBatchXF"
          >
            取消
          </van-button>
        </div>
      </div>
    </van-dialog>

    <OrganizationalWithLeafUserOne
      ref="PopupDepartmentUserRefXfConfirm"
      :main-key="xfConfirmSessionKey"
      @receive-from-child="getXfConfirmUser"
    />
  </div>
</template>

<script setup>
import { ref, computed, getCurrentInstance } from 'vue';
import { showConfirmDialog, showSuccessToast, showToast } from 'vant';
import OrganizationalWithLeafUserOne from '@/components/OrganizationalWithLeafUserOne.vue';
import { workflowSubmit } from '@/tools/workflow.js';
import { guid } from '@/utils/commonMethod.js';
import {
  dispatchSingleXF,
  fetchTaskResultItems,
  resolveHdConfirmVar,
  validateBatchXF,
} from '@/view/safeCheck/checkDispatch.js';

const { proxy } = getCurrentInstance();

const onClickLeft = () => {
  history.back();
};
const headers = ref({
  token: localStorage.getItem('token'),
  userId: localStorage.getItem('userId'),
  dept: JSON.parse(localStorage.getItem('dept'))[0].deptCode
});

const tableData = ref([]);
const deleteDialogVisible = ref(false);
const currentDeleteItem = ref([]);

const kz = ref(true);
const handAdd = async () => {
  kz.value = false;
  resetForma();
  proxy.$router.push({
    path: '/safeCheck/safeCheckTaskEdit'
  });
};

const form = ref({
  taskTemplateId: '',
  checkType: '',
  checkedDept: '',
  notes: '',
  checkedDeptCode: '',
  checkThing: '',
  checkPerson: '',
  checkTime: ''
});
const resetForma = () => {
  form.value = {
    taskTemplateId: '',
    checkType: '',
    checkedDept: '',
    notes: '',
    checkedDeptCode: '',
    checkThing: '',
    checkPerson: '',
    checkTime: ''
  };
};

const isRefreshing = ref(false);
const isLoading = ref(false);
const isFinished = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const totalRows = ref(0);
const resultData = ref([]);
const query = ref({
  taskTemplateId: '',
  checkedDept: '',
  checkPerson: '',
  checkedDeptCode: '',
  checkThing: '',
  checkPersonName: ''
});

const getTableData = async () => {
  const url = 'sgsafe/CheckTask/query';
  const param = {
    page: currentPage.value,
    rows: pageSize.value,
    params: JSON.stringify(query.value)
  };
  const response = await proxy.$axios.get(url, param);
  if (response.data.code === 0) {
    tableData.value = response.data.data.records;
    totalRows.value = response.data.data.total;
    tableData.value.forEach(item => {
      switch (item.status) {
        case '0':
          item.status = '隐患登记';
          break;
        case '1':
          item.status = '隐患分析确认';
          break;
        case '2':
          item.status = '隐患整改';
          break;
        case '3':
          item.status = '隐患验收';
          break;
        case '4':
          item.status = '隐患销号';
          break;
        case '5':
          item.status = '结束';
          break;
        case '-1':
          item.status = '待提交';
          break;
      }
    });
  } else {
    showToast({
      type: 'fail',
      message: '操作失败！' + response.data.msg
    });
  }
};

const onRefresh = () => {
  basicReset();
  onLoad();
};

const onLoad = async () => {
  if (isRefreshing.value) {
    resultData.value = [];
    currentPage.value = 1;
    isRefreshing.value = false;
  }
  try {
    await getTableData();
    if (pageSize.value * currentPage.value < totalRows.value) {
      resultData.value = [...resultData.value, ...tableData.value];
      currentPage.value++;
    } else {
      resultData.value = [...resultData.value, ...tableData.value];
      isFinished.value = true;
    }
  } catch (error) {
    console.log(error);
    isFinished.value = true;
  } finally {
    isLoading.value = false;
  }
};

const basicReset = () => {
  isFinished.value = false;
  isLoading.value = true;
  currentPage.value = 1;
  resultData.value = [];
};

const confirmDelete = () => {
  var url = '/sgsafe/CheckTask/remove';
  var param = {
    id: JSON.stringify(currentDeleteItem.value.map(x => x.id))
  };
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == 0) {
      showToast({
        type: 'success',
        message: '删除成功'
      });
      getTableData();
      deleteDialogVisible.value = false;
      currentDeleteItem.value = [];
    } else {
      showToast({
        type: 'fail',
        message: '操作失败！' + response.data.msg
      });
    }
  });
};

const edits = (row) => {
  kz.value = true;
  form.value = { ...row };
  proxy.$router.push({
    path: '/safeCheck/safeCheckTaskItem',
    query: {
      id: form.value.id
    }
  });
};

/** 一键下发 */
const dialogBatchXFVisible = ref(false);
const batchPendingItems = ref([]);
const batchSubmitting = ref(false);
const xfConfirmUserCode = ref('');
const xfConfirmUserDesc = ref('');
const xfConfirmSessionKey = ref(guid());
const PopupDepartmentUserRefXfConfirm = ref(null);

const xfConfirmDisplay = computed(() => {
  if (xfConfirmUserDesc.value && xfConfirmUserCode.value) {
    return `${xfConfirmUserDesc.value}（${xfConfirmUserCode.value}）`;
  }
  return xfConfirmUserDesc.value || xfConfirmUserCode.value || '';
});

const resetXfConfirm = () => {
  xfConfirmUserCode.value = '';
  xfConfirmUserDesc.value = '';
};

const openXfConfirmPicker = () => {
  PopupDepartmentUserRefXfConfirm.value?.open();
};

const getXfConfirmUser = (item) => {
  if (!item?.user?.userCode) {
    showToast({ type: 'fail', message: '请选择有效的隐患确认人' });
    return;
  }
  xfConfirmUserCode.value = item.user.userCode;
  xfConfirmUserDesc.value = item.user.userDesc || item.user.userName || '';
};

const handleBatchXF = async (row) => {
  try {
    const items = await fetchTaskResultItems(proxy.$axios, row.id, headers.value.userId);
    if (!items.length) {
      showToast({ type: 'fail', message: '该任务下没有检查项' });
      return;
    }
    const validation = validateBatchXF(items);
    if (!validation.ok) {
      showToast({ type: 'fail', message: validation.message });
      return;
    }
    batchPendingItems.value = validation.pending;
    xfConfirmSessionKey.value = guid();
    resetXfConfirm();
    dialogBatchXFVisible.value = true;
  } catch (error) {
    showToast({
      type: 'fail',
      message: '加载检查项失败：' + (error.message || '未知错误'),
    });
  }
};

const confirmBatchXF = async () => {
  if (!xfConfirmUserCode.value) {
    showToast({ type: 'fail', message: '请选择隐患确认人' });
    return;
  }
  const items = batchPendingItems.value;
  if (!items.length) {
    showToast({ type: 'fail', message: '没有待下发的不符合项' });
    return;
  }
  try {
    await showConfirmDialog({
      title: '一键下发',
      message: `将为该任务下发 ${items.length} 条不符合项，隐患确认人：${xfConfirmDisplay.value}，确定继续吗？`,
    });
  } catch {
    return;
  }

  const hdConfirmVar = await resolveHdConfirmVar(proxy.$axios, xfConfirmUserCode.value);
  if (!hdConfirmVar) {
    showToast({ type: 'fail', message: '未能解析隐患确认人，无法提交审批' });
    return;
  }

  batchSubmitting.value = true;
  let successCount = 0;
  let failCount = 0;
  for (const item of items) {
    try {
      await dispatchSingleXF(
        proxy.$axios,
        workflowSubmit,
        item,
        xfConfirmUserCode.value,
        xfConfirmUserDesc.value,
        hdConfirmVar,
      );
      successCount++;
    } catch (error) {
      failCount++;
      console.error('单条下发失败:', item.id, error);
    }
  }
  batchSubmitting.value = false;
  dialogBatchXFVisible.value = false;
  resetXfConfirm();

  if (failCount === 0) {
    showSuccessToast(`一键下发完成，共 ${successCount} 条`);
  } else {
    showToast({
      type: 'fail',
      message: `下发结束：成功 ${successCount} 条，失败 ${failCount} 条`,
    });
  }
};

const cancelBatchXF = () => {
  if (batchSubmitting.value) {
    return;
  }
  dialogBatchXFVisible.value = false;
  resetXfConfirm();
};

</script>

<style scoped>
.h5-container {
  width: 100%;
  padding: 5px;
  box-sizing: border-box;
}

.card {
  margin: 10px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  background-color: #fff;
}

.label-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.cell-title {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.5;
  max-height: calc(1.5em * 2);
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.batch-xf-body {
  padding: 8px 0 4px;
}

.batch-xf-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 12px 16px 4px;
}
</style>
