<template>
  <a-spin :spinning="loading">
    <div class="dq-inspect-task-bpm-form">
      <a-form
        class="main-form"
        :class="{ 'main-form-readonly': mainDisabled }"
        labelAlign="left"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        :model="mainForm"
      >
        <div class="base-info-header section-toolbar">
          <div class="section-title">基础信息</div>
          <a-space class="section-actions">
            <a-button v-if="!mainDisabled" class="base-save-button" type="link" size="small" :loading="savingMain" @click="submitForm">
              <Icon icon="ant-design:save-outlined" />
              保存
            </a-button>
            <a-button
              class="section-action-button"
              :type="showBaseInfoDetail ? 'default' : 'link'"
              size="small"
              @click="showBaseInfoDetail = !showBaseInfoDetail"
            >
              <Icon :icon="showBaseInfoDetail ? 'ant-design:up-outlined' : 'ant-design:down-outlined'" />
              {{ showBaseInfoDetail ? '收起基础信息' : '展开全部信息' }}
            </a-button>
          </a-space>
        </div>
        <a-row class="base-info-row" :gutter="[12, 4]">
          <a-col :span="24">
            <a-form-item label="具体问题" name="problemId" :labelCol="{ xs: { span: 24 }, sm: { span: 4 } }" :wrapperCol="{ xs: { span: 24 }, sm: { span: 20 } }">
              <a-tree-select
                v-model:value="mainForm.problemId"
                :tree-data="problemTreeData"
                :loading="loadingProblemOptions"
                :disabled="mainDisabled"
                placeholder="请选择具体问题"
                allow-clear
                tree-default-expand-all
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="整改措施" name="improveMeasure" :labelCol="{ xs: { span: 24 }, sm: { span: 4 } }" :wrapperCol="{ xs: { span: 24 }, sm: { span: 20 } }">
              <a-textarea v-model:value="mainForm.improveMeasure" :auto-size="{ minRows: 1, maxRows: 4 }" :disabled="mainDisabled" allow-clear />
            </a-form-item>
          </a-col>
          <template v-if="showBaseInfoDetail">
            <a-col :span="12">
              <a-form-item label="密级" name="secretLevel">
                <j-dict-select-tag v-model:value="mainForm.secretLevel" dictCode="secret_level" placeholder="请选择密级" :disabled="mainDisabled" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="完成时限" name="deadline">
                <a-date-picker v-model:value="mainForm.deadline" value-format="YYYY-MM-DD" :disabled="mainDisabled" style="width: 100%" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="目标节点" name="targetNode">
                <a-input v-model:value="mainForm.targetNode" :disabled="mainDisabled" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="措施责任领导" name="measureResLeader">
                <j-select-user v-model:value="mainForm.measureResLeader" :disabled="mainDisabled" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="措施责任部门" name="measureResDept">
                <j-select-dept v-model:value="mainForm.measureResDept" :disabled="mainDisabled" :multiple="true" checkStrictly allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="分管所领导" name="chargeLeaderId">
                <a-input v-if="mainDisabled" :value="mainForm.chargeLeaderId" disabled />
                <j-select-user v-else v-model:value="mainForm.chargeLeaderId" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="整改交付成果" name="rectificationEvidence">
                <a-input v-model:value="mainForm.rectificationEvidence" :disabled="mainDisabled" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="成效评价标准" name="evaluationCriterion">
                <a-input v-model:value="mainForm.evaluationCriterion" :disabled="mainDisabled" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="是否需要党群领导审批" name="isNeedAppro">
                <j-dict-select-tag type="radio" v-model:value="mainForm.isNeedAppro" dictCode="yn" :disabled="mainDisabled" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="党群领导" name="supDeptleaderid">
                <j-select-user v-model:value="mainForm.supDeptleaderid" :disabled="mainDisabled" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="检查情况" name="inspectionStatus">
                <a-input v-model:value="mainForm.inspectionStatus" :disabled="mainDisabled" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="监督意见" name="supervisoryOpinion">
                <a-input v-model:value="mainForm.supervisoryOpinion" :disabled="mainDisabled" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="整改状态" name="taskStatus">
                <a-input v-model:value="mainForm.taskStatus" :disabled="mainDisabled" allow-clear />
              </a-form-item>
            </a-col>
          </template>
        </a-row>
      </a-form>

      <a-divider />

      <div class="feedback-header section-toolbar" v-if="showFeedbackInfo">
        <div class="section-title">反馈信息</div>
        <a-space class="section-actions">
          <a-button v-if="showAddFeedback" class="section-action-button feedback-add-button" type="primary" @click="openFeedbackModal">
            <Icon icon="ant-design:plus-outlined" />
            新增反馈
          </a-button>
          <a-button
            class="section-action-button"
            :type="showFeedbackDetail ? 'default' : 'link'"
            size="small"
            @click="showFeedbackDetail = !showFeedbackDetail"
          >
            <Icon :icon="showFeedbackDetail ? 'ant-design:up-outlined' : 'ant-design:down-outlined'" />
            {{ showFeedbackDetail ? '收起反馈信息' : '展开反馈信息' }}
          </a-button>
        </a-space>
      </div>
      <a-table
        v-if="showFeedbackInfo && showFeedbackDetail"
        rowKey="id"
        size="small"
        bordered
        :columns="feedbackColumns"
        :data-source="feedbackList"
        :pagination="false"
        :scroll="{ x: 1200 }"
      >
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.key === 'seq'">{{ index + 1 }}</template>
          <template v-if="column.key === 'attachments'">
            <SUploadFile v-if="record.id" class="feedback-attachment-list" :bussiness-id="record.id" :disabled="true" :multiple="true" />
            <span v-else>-</span>
          </template>
          <template v-if="column.key === 'feedbackAction'">
            <a-button type="link" size="small" @click="handleEditFeedback(record)">编辑</a-button>
            <a-popconfirm title="确定删除该反馈吗？" @confirm="handleDeleteFeedback(record)">
              <a-button type="link" size="small" danger>删除</a-button>
            </a-popconfirm>
          </template>
        </template>
      </a-table>

      <DqInspectTaskBPMFeedbackModal
        ref="feedbackModalRef"
        :showJiJianFields="showJiJianFields"
        :jiJianFieldsReadonly="jiJianFieldsReadonly"
        :nonJiJianFieldsReadonly="nonJiJianFieldsReadonly"
        @success="loadFeedbackList"
      />

      <template v-if="showProcessHandle">
        <a-divider />
        <div class="process-header section-toolbar">
          <div class="section-title">流程办理</div>
        </div>
        <a-form v-if="showSubApproveUser" class="process-variable-form" labelAlign="left" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="是否办结" :labelCol="wideLabelCol" :wrapperCol="wideWrapperCol">
                <a-radio-group v-model:value="isEnd" :disabled="savingSubApproveUser">
                  <a-radio :value="0">否（分配部门经办人）</a-radio>
                  <a-radio :value="1">是（办结）</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col v-if="showSubApproveUserSelector" :span="12">
              <a-form-item label="部门经办人" :labelCol="wideLabelCol" :wrapperCol="wideWrapperCol">
                <j-select-user v-model:value="subApproveUser" :disabled="savingSubApproveUser" allow-clear />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
        <a-form v-if="showIsNeedLeaderApprove" class="process-variable-form" labelAlign="left" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="是否需要所领导审批" :labelCol="wideLabelCol" :wrapperCol="wideWrapperCol">
                <a-radio-group v-model:value="isNeedLeaderApprove" :disabled="savingIsNeedLeaderApprove">
                  <a-radio :value="0">否（不需要）</a-radio>
                  <a-radio :value="1">是（需要所领导审批）</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col v-if="showIsNeedLeaderApproveSelector" :span="12">
              <a-form-item label="分管所领导" :labelCol="wideLabelCol" :wrapperCol="wideWrapperCol">
                <j-select-user v-model:value="leaderApproveUser" :disabled="savingIsNeedLeaderApprove" allow-clear />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
        <TaskHandleInnerContent
          :form-data="formData"
          :claim="claim"
          :showSelnextUser="showSelnextUser"
          :beforeHandle="saveMainFormBeforeProcessHandle"
          @success="handleProcessSuccess"
          @claimSuccess="handleClaimSuccess"
        />
      </template>
    </div>
  </a-spin>
</template>

<script lang="ts" setup>
  import { computed, onMounted, reactive, ref, watch } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useUserStore } from '/@/store/modules/user';
  import JSelectDept from '/@/components/Form/src/jeecg/components/JSelectDept.vue';
  import JSelectUser from '/@/components/Form/src/jeecg/components/JSelectUser.vue';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import Icon from '/@/components/Icon/index';
  import { saveBpmForm, setProcessVariable, specificProblemOptions } from '../DqInspectTask.api';
  import { list as progressList, deleteOne as progressDelete } from '../../inspectProgress/DqInspectProgress.api';
  import { usePermission } from '/@/hooks/web/usePermission';
  import TaskHandleInnerContent from '/@/views/super/bpm/process/personalOffice/myHandleTask/content/TaskHandleInnerContent.vue';
  import DqInspectTaskBPMFeedbackModal from './DqInspectTaskBPMFeedbackModal.vue';
  import SUploadFile from '/@/components/semri/fileComponent/SUploadFile.vue';

  const { initBpmFormData } = usePermission();
  const userStore = useUserStore();

  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({}) },
    formBpm: { type: Boolean, default: true },
    claim: { type: Boolean, default: false },
  });

  initBpmFormData(props.formData);

  const emit = defineEmits(['ok', 'success', 'claimSuccess']);
  const { createMessage } = useMessage();
  const queryByIdUrl = '/dqinspecttask/dqInspectTask/queryById';

  const labelCol = { xs: { span: 24 }, sm: { span: 7 } };
  const wrapperCol = { xs: { span: 24 }, sm: { span: 17 } };
  const wideLabelCol = { xs: { span: 24 }, sm: { span: 3 } };
  const wideWrapperCol = { xs: { span: 24 }, sm: { span: 21 } };

  const feedbackModalRef = ref();
  const loading = ref(false);
  const savingMain = ref(false);
  const savingSubApproveUser = ref(false);
  const showBaseInfoDetail = ref(true);
  const showFeedbackDetail = ref(true);
  const feedbackList = ref<any[]>([]);
  const subApproveUser = ref('');
  const isEnd = ref(0);
  const problemTreeData = ref<any[]>([]);
  const loadingProblemOptions = ref(false);
  const isNeedLeaderApprove = ref(0);
  const leaderApproveUser = ref('');
  const savingIsNeedLeaderApprove = ref(false);

  const mainForm = reactive<Record<string, any>>({
    id: '',
    problemId: '',
    secretLevel: '',
    improveMeasure: '',
    deadline: '',
    targetNode: '',
    measureResLeader: '',
    measureResDept: '',
    chargeLeaderId: '',
    rectificationEvidence: '',
    evaluationCriterion: '',
    isNeedAppro: '',
    supDeptleaderid: '',
    inspectionStatus: '',
    supervisoryOpinion: '',
    measureCount: undefined,
    bpmProcessId: '',
    bpmStatus: '',
    taskStatus: '',
    superviseCount: '',
    sortNo: undefined,
  });

  const feedbackColumns = computed(() => {
    const cols: any[] = [
      { title: '序号', key: 'seq', align: 'center', width: 60 },
      { title: '反馈人', dataIndex: 'feedbackPersonName', align: 'center', width: 100 },
      { title: '反馈部门', dataIndex: 'feedbackDeptName', align: 'center', width: 140 },
      { title: '工作进展', dataIndex: 'workProgress', align: 'left', width: 240 },
      { title: '实际完成时间', dataIndex: 'actualTime', align: 'center', width: 120 },
      { title: '进展状态', dataIndex: 'bpmStatus_dictText', align: 'center', width: 100 },
      { title: '附件', dataIndex: 'id', key: 'attachments', align: 'left', width: 280 },
    ];
    if (showJiJianFields.value) {
      cols.push(
        { title: '检查情况', dataIndex: 'inspectionStatus', align: 'left', width: 160 },
        { title: '监督意见', dataIndex: 'supervisoryOpinion', align: 'left', width: 160 },
        { title: '措施数量', dataIndex: 'measureCount', align: 'center', width: 100 }
      );
    }
    if (showEditFeedback.value) {
      cols.push({ title: '操作', dataIndex: 'id', key: 'feedbackAction', align: 'center', width: 120, fixed: 'right' });
    }
    return cols;
  });

  const mainDisabled = computed(() => {
    if (props.formBpm) {
      return props.formData?.disabled !== false;
    }
    return props.formDisabled;
  });
  const showProcessHandle = computed(() => {
    const explicit = props.formData?.extendUrlParams?.showProcessHandle;
    if (explicit === '0') return false;
    if (explicit === '1') return true;
    return props.formBpm && !!props.formData?.taskId;
  });
  const showAddFeedback = computed(
    () => String(props.formData?.extendUrlParams?.showAddFeedback ?? '') === '1'
  );
  const showFeedbackInfo = computed(() => {
    const p = props.formData?.extendUrlParams;
    const explicit = p?.showFeedbackInfo;
    if (explicit === '0') return false;
    if (explicit === '1') return true;
    return (
      String(p?.showAddFeedback ?? '') === '1' ||
      String(p?.showEditFeedback ?? '') === '1' ||
      String(p?.showDeptFeedback ?? '') === '1'
    );
  });
  const showEditFeedback = computed(
    () => String(props.formData?.extendUrlParams?.showEditFeedback ?? '') === '1'
  );
  const showDeptFeedback = computed(
    () => String(props.formData?.extendUrlParams?.showDeptFeedback ?? '') === '1'
  );
  const showJiJianFields = computed(() => String(props.formData?.extendUrlParams?.showJiJianFields ?? '') === '1');
  const jiJianFieldsReadonly = computed(() => String(props.formData?.extendUrlParams?.jiJianFieldsReadonly ?? '') === '1');
  const nonJiJianFieldsReadonly = computed(() => String(props.formData?.extendUrlParams?.nonJiJianFieldsReadonly ?? '') === '1');
  const showSelnextUser = computed(() => String(props.formData?.extendUrlParams?.showSelnextUser ?? '') === '1');
  const showSubApproveUser = computed(
    () => String(props.formData?.extendUrlParams?.showSubApproveUser ?? '') === '1'
  );
  const showIsNeedLeaderApprove = computed(
    () => String(props.formData?.extendUrlParams?.showIsNeedLeaderApprove ?? '') === '1'
  );
  const showSubApproveUserSelector = computed(() => showSubApproveUser.value && String(isEnd.value) !== '1');
  const showIsNeedLeaderApproveSelector = computed(() => showIsNeedLeaderApprove.value && String(isNeedLeaderApprove.value) === '1');

  const processInfo = computed(() => ({
    taskId: props.formData?.taskId,
    taskDefKey: props.formData?.taskDefKey,
    processInstanceId:
      props.formData?.procInsId ||
      props.formData?.procInstId ||
      props.formData?.processInstanceId ||
      props.formData?.vars?.BPM_INST_ID ||
      props.formData?.vars?.JG_LOCAL_PROCESS_ID ||
      props.formData?.vars?.process_inst_id ||
      props.formData?.vars?.processInstanceId,
    processDataId: props.formData?.processDataId,
    processTableName: props.formData?.processTableName,
  }));

  onMounted(() => {
    initFormData();
  });

  watch([() => props.formData?.dataId, () => processInfo.value.processInstanceId], () => initFormData());

  watch(showDeptFeedback, () => {
    loadFeedbackList();
  });

  watch(
    () => props.formData?.vars?.isEnd,
    (value) => {
      isEnd.value = String(value ?? '0') === '1' ? 1 : 0;
    },
    { immediate: true }
  );

  watch(
    () => props.formData?.vars?.isNeedLeaderApprove,
    (value) => {
      isNeedLeaderApprove.value = String(value ?? '0') === '1' ? 1 : 0;
    },
    { immediate: true }
  );

  async function loadProblemTree() {
    loadingProblemOptions.value = true;
    try {
      const data = await specificProblemOptions();
      problemTreeData.value = Array.isArray(data) ? data : data?.result || [];
    } finally {
      loadingProblemOptions.value = false;
    }
  }

  async function initFormData() {
    const dataId = props.formData?.dataId;
    if (!dataId) return;
    showBaseInfoDetail.value = true;
    loading.value = true;
    try {
      await loadProblemTree();
      const data = await defHttp.get({ url: queryByIdUrl, params: { id: dataId } });
      setMainForm(data || {});
      leaderApproveUser.value = mainForm.chargeLeaderId || '';
      await loadFeedbackList();
    } finally {
      loading.value = false;
    }
  }

  function setMainForm(record: Record<string, any>) {
    Object.keys(mainForm).forEach((key) => {
      mainForm[key] = record[key] ?? '';
    });
  }

  function getCurrentUserDeptId() {
    const userInfo = (userStore.getUserInfo || {}) as Record<string, any>;
    const loginInfo = (userStore.getLoginInfo || {}) as Record<string, any>;
    const departs = Array.isArray(loginInfo.departs) ? loginInfo.departs : [];
    if (userInfo.orgCode) {
      const dept = departs.find((item: any) => item.orgCode === userInfo.orgCode);
      return dept?.id || '';
    }
    return departs.length === 1 ? departs[0]?.id || '' : '';
  }

  async function loadFeedbackList() {
    const bpmProcessId = processInfo.value.processInstanceId;
    if (!mainForm.id) {
      feedbackList.value = [];
      return;
    }
    const res = await progressList({ mainId: mainForm.id, pageNo: 1, pageSize: 999, column: 'createTime', order: 'desc' });
    let list = Array.isArray(res) ? res : res?.records || [];
    if (list.length && showDeptFeedback.value) {
      const deptId = getCurrentUserDeptId();
      if (deptId) {
        list = list.filter((item: any) => {
          const deptIds = String(item.feedbackDeptId || '').split(',').map((s: string) => s.trim());
          return deptIds.includes(String(deptId));
        });
      }
    }
    feedbackList.value = list;
  }

  async function submitForm() {
    return saveMainForm();
  }

  async function saveMainForm(options: { showMessage?: boolean; emitOk?: boolean } = {}) {
    const { showMessage = true, emitOk = true } = options;
    savingMain.value = true;
    try {
      const processInstanceId = processInfo.value.processInstanceId;
      const res = await saveBpmForm({
        processInstanceId,
        varField: 'json_data',
        formData: { ...mainForm },
      });
      if (res.success) {
        if (showMessage) createMessage.success(res.message || '保存成功');
        if (emitOk) emit('ok');
        return true;
      }
      createMessage.warning(res.message || '保存失败');
      return false;
    } catch {
      createMessage.warning('保存失败');
      return false;
    } finally {
      savingMain.value = false;
    }
  }

  async function saveMainFormBeforeProcessHandle() {
    if (!mainDisabled.value) {
      const mainSaved = await saveMainForm({ showMessage: false, emitOk: false });
      if (!mainSaved) return false;
    }
    if (showSubApproveUser.value) {
      const result = await saveSubApproveUserVariable({ showSuccessMessage: false });
      if (!result) return false;
    }
    if (showIsNeedLeaderApprove.value) {
      const result = await saveIsNeedLeaderApproveVariable({ showSuccessMessage: false });
      if (!result) return false;
    }
    return true;
  }

  function openFeedbackModal() {
    if (!mainForm.id) {
      createMessage.warning('主表数据不存在，无法新增反馈');
      return;
    }
    const processInstanceId = processInfo.value.processInstanceId;
    feedbackModalRef.value?.open(mainForm.id, processInstanceId);
  }

  function handleEditFeedback(record) {
    feedbackModalRef.value?.openEdit(record);
  }

  async function handleDeleteFeedback(record) {
    if (!record.id) {
      createMessage.warning('反馈记录ID不存在');
      return;
    }
    await progressDelete({ id: record.id }, loadFeedbackList);
  }

  async function saveSubApproveUserVariable(options: { showSuccessMessage?: boolean } = {}) {
    const { showSuccessMessage = true } = options;
    const processInstanceId = processInfo.value.processInstanceId;
    const isEndValue = String(isEnd.value);
    const usernameValue = normalizeUsernameList(subApproveUser.value);
    if (!processInstanceId) {
      createMessage.warning('流程实例ID不能为空');
      return false;
    }
    if (isEndValue !== '1' && !usernameValue) {
      createMessage.warning('请选择部门经办人');
      return false;
    }

    savingSubApproveUser.value = true;
    try {
      const isEndResult = await saveProcessVariable('is_end', isEndValue);
      if (!isEndResult?.success) {
        createMessage.warning(isEndResult.message || '保存失败');
        return false;
      }

      if (isEndValue !== '1') {
        const subApproveUserResult = await saveProcessVariable('sub_approve_user', usernameValue);
        if (!subApproveUserResult?.success) {
          createMessage.warning(subApproveUserResult.message || '保存失败');
          return false;
        }
      }
      if (showSuccessMessage) createMessage.success('保存成功');
      return true;
    } catch {
      createMessage.warning('保存失败');
      return false;
    } finally {
      savingSubApproveUser.value = false;
    }
  }

  function saveProcessVariable(varField: string, varVal: any) {
    return setProcessVariable({
      processInstanceId: processInfo.value.processInstanceId,
      local: false,
      varField,
      varVal,
    });
  }

  function normalizeUsernameList(value: string) {
    return String(value || '')
      .split(',')
      .map((item) => item.trim())
      .filter(Boolean)
      .join(',');
  }

  async function saveIsNeedLeaderApproveVariable(options: { showSuccessMessage?: boolean } = {}) {
    const { showSuccessMessage = true } = options;
    const processInstanceId = processInfo.value.processInstanceId;
    const isNeedLeaderApproveValue = String(isNeedLeaderApprove.value);
    const leaderUsernameValue = normalizeUsernameList(leaderApproveUser.value);
    if (!processInstanceId) {
      createMessage.warning('流程实例ID不能为空');
      return false;
    }
    if (isNeedLeaderApproveValue === '1' && !leaderUsernameValue) {
      createMessage.warning('请选择分管所领导');
      return false;
    }

    savingIsNeedLeaderApprove.value = true;
    try {
      const result = await saveProcessVariable('is_need_leader_approve', isNeedLeaderApproveValue);
      if (!result?.success) {
        createMessage.warning(result.message || '保存失败');
        return false;
      }
      if (isNeedLeaderApproveValue === '1') {
        const leaderResult = await saveProcessVariable('leader_approve_user', leaderUsernameValue);
        if (!leaderResult?.success) {
          createMessage.warning(leaderResult.message || '保存失败');
          return false;
        }
      }
      if (showSuccessMessage) createMessage.success('保存成功');
      return true;
    } catch {
      createMessage.warning('保存失败');
      return false;
    } finally {
      savingIsNeedLeaderApprove.value = false;
    }
  }

  function handleProcessSuccess() {
    emit('success');
  }

  function handleClaimSuccess() {
    emit('claimSuccess');
  }

  defineExpose({
    submitForm,
    initFormData,
    loadFeedbackList,
  });
</script>

<style lang="less" scoped>
  .dq-inspect-task-bpm-form {
    padding: 8px 12px 14px;
  }

  .main-form {
    background: #fff;
  }

  .main-form,
  .process-variable-form {
    :deep(.ant-form-item-label) {
      text-align: left;
    }

    :deep(.ant-form-item-label > label) {
      justify-content: flex-start;
      color: #1f2937;
      font-weight: 500;
    }

    :deep(.ant-form-item-control),
    :deep(.ant-form-item-control-input),
    :deep(.ant-form-item-control-input-content) {
      text-align: left;
    }
  }

  .section-title {
    margin-bottom: 8px;
    padding-left: 8px;
    border-left: 3px solid #1677ff;
    color: #1f2937;
    font-size: 14px;
    font-weight: 600;
    line-height: 16px;
  }

  .section-toolbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 8px;
    padding: 6px 10px;
    background: #f6fbff;
    border: 1px solid #d6e8ff;
    border-radius: 6px;

    .section-title {
      margin-bottom: 0;
    }

    .section-actions {
      display: inline-flex;
      align-items: center;
      gap: 4px;
    }

    .section-action-button {
      display: inline-flex;
      align-items: center;
      gap: 4px;
      min-width: 58px;
      justify-content: center;
      font-weight: 500;
      box-shadow: none;
    }

    .base-save-button {
      display: inline-flex;
      align-items: center;
      gap: 4px;
      height: 24px;
      padding: 0 6px;
      color: #64748b;
      font-weight: 400;
    }
  }

  .base-info-header {
    margin-top: 0;
  }

  .base-info-row {
    padding: 0 10px;

    :deep(.ant-form-item) {
      margin-bottom: 6px;
    }

    :deep(.ant-form-item-label) {
      padding-bottom: 0;
    }

    :deep(.ant-form-item-label > label) {
      width: 100%;
    }

    :deep(.ant-input),
    :deep(.ant-input-number),
    :deep(.ant-picker),
    :deep(.ant-select-selector) {
      min-height: 30px;
    }
  }

  .main-form-readonly {
    :deep(.ant-input[disabled]),
    :deep(.ant-input-disabled),
    :deep(.ant-input-affix-wrapper-disabled),
    :deep(.ant-input-affix-wrapper-disabled.ant-input-outlined),
    :deep(.ant-input-affix-wrapper-disabled:hover),
    :deep(.ant-input-affix-wrapper-disabled:focus),
    :deep(.ant-input-affix-wrapper-disabled-focused),
    :deep(.ant-input-outlined[disabled]),
    :deep(.ant-input-outlined.ant-input-disabled),
    :deep(textarea.ant-input[disabled]),
    :deep(.ant-input-number-disabled),
    :deep(.ant-input-number-disabled:hover),
    :deep(.ant-input-number-disabled:focus),
    :deep(.ant-picker-disabled),
    :deep(.ant-select-disabled .ant-select-selector) {
      background: transparent !important;
      border-color: transparent !important;
      color: #1f2937 !important;
      box-shadow: none !important;
      cursor: default !important;
      opacity: 1 !important;
    }

    :deep(.ant-input[disabled]),
    :deep(.ant-input-disabled),
    :deep(.ant-input-affix-wrapper-disabled),
    :deep(.ant-input-number-disabled),
    :deep(textarea.ant-input[disabled]) {
      padding-left: 0 !important;
      padding-right: 0 !important;
    }

    :deep(.ant-input-affix-wrapper-disabled .ant-input) {
      background: transparent !important;
      color: #1f2937 !important;
      cursor: default !important;
    }

    :deep(.ant-input-number-disabled .ant-input-number-input) {
      background: transparent !important;
      color: #1f2937 !important;
      -webkit-text-fill-color: #1f2937 !important;
      cursor: default !important;
    }

    :deep(.ant-input[disabled]::placeholder),
    :deep(.ant-input-disabled::placeholder),
    :deep(.ant-input-affix-wrapper-disabled .ant-input::placeholder) {
      color: #9ca3af !important;
    }

    :deep(.ant-picker-disabled input),
    :deep(.ant-select-disabled .ant-select-selection-item),
    :deep(.ant-select-disabled .ant-select-selection-item span),
    :deep(.ant-select-disabled .ant-select-selection-placeholder),
    :deep(.ant-select-disabled .ant-select-selection-placeholder span) {
      color: #1f2937 !important;
      -webkit-text-fill-color: #1f2937 !important;
      cursor: default !important;
    }

    :deep(.ant-picker-disabled),
    :deep(.ant-select-disabled .ant-select-selector) {
      padding-left: 0 !important;
    }

    :deep(.ant-select-disabled),
    :deep(.ant-select-disabled *),
    :deep(.ant-select-disabled.ant-select-outlined),
    :deep(.ant-select-disabled.ant-select-outlined .ant-select-selector) {
      color: #1f2937 !important;
      -webkit-text-fill-color: #1f2937 !important;
      opacity: 1 !important;
    }

    :deep(.ant-select-disabled .ant-select-arrow),
    :deep(.ant-picker-disabled .ant-picker-suffix),
    :deep(.ant-input-disabled .ant-input-clear-icon),
    :deep(.ant-input-affix-wrapper-disabled .ant-input-clear-icon),
    :deep(.ant-input-number-disabled .ant-input-number-handler-wrap),
    :deep(.ant-select-disabled .ant-select-clear) {
      display: none;
    }

    :deep(.ant-radio-wrapper-disabled) {
      color: #1f2937 !important;
      cursor: default !important;
    }

    :deep(.ant-radio-wrapper-disabled:not(.ant-radio-wrapper-checked)) {
      display: none;
    }

    :deep(.ant-radio-disabled .ant-radio-inner) {
      display: none;
    }
  }

  .feedback-header {
    margin-bottom: 8px;

    .feedback-add-button {
      min-width: 104px;
    }
  }

  .process-variable-form {
    margin-bottom: 8px;
  }

  :deep(.ant-divider-horizontal) {
    margin: 10px 0;
  }

  .feedback-attachment-list {
    min-width: 240px;

    :deep(.file-list-wrapper) {
      min-height: 36px;
      max-height: 130px;
      overflow-y: auto;
      padding: 4px 8px;
    }

    :deep(.file-list-header) {
      margin-bottom: 6px;
      padding-bottom: 6px;
    }

    :deep(.file-list .file-item) {
      padding: 8px;
      margin-bottom: 6px;
    }

    :deep(.ant-empty) {
      margin: 0;
      padding: 4px 0;

      .ant-empty-image {
        display: none;
      }

      .ant-empty-description {
        font-size: 12px;
        color: #999;
        padding: 0;
        margin: 0;
      }
    }
  }
</style>
